SOLID Principles: Single Responsibility Principle (SRP)

Image for post
  • A class should have only one reason to change.
  • this means that a class should not be loaded with multiple responsibilities and a single responsibility should not be spread across multiple classes or mixed with other responsibilities.
  • The reason is that the more changes requested in the future, the more changes the class needs to apply.
  • Example:
Image for post
Image for post

chief financial officer (CFO), chief operating officer (COO), chief technology officer (CTO) responsible for Calculate payments, reports, and save data to the database respectively.

if we put all this logic into Employee class like that:

we will face a problem, and this problem is Employee class takes care of three different Responsibilities (the logic of calculate payments, save Employee data to the database, and create reports). we solve it by creating three different classes and make every class have Single Responsibility.

So what is the problem with putting all together?

if you work on a small project individually, you will see this, not a big deal to have all logic in one place, but in large scale projects, there will a lot of cases for every method so for example calculatePay metho may depend on many methods based on the case (each case have the different calculation), so the bigger project is the bigger logic needed, and in huge companies, there is a team responsible for every part of project logic.

So in this example:

  • The calculatePay() method is specified by the accounting department, which reports to the CFO.
  • The reportHours() method is specified and used by the human resources department, which reports to the COO.
  • The save() method is specified by the database administrators, who report to the CTO.

For this reason, it not wise to put all logic in one place.

Image for post
Image for post

And this will be the new structure now all logic is separated from each other, and have employee data shared across them.

So now every team can work fine with their scope of the project without affecting other parts of the project.

But this leads to another problem which is developers now have three classes that they have to instantiate. A common solution to this solve this problem is to use the Facade pattern.

Image for post
Image for post
Facade pattern

Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.

and after apply SRP the code will be something like that:

continuo to the rest of SOLID

Written by

Software engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store