The Single Responsibility Principle

Classes should have one responsibility

The essence of the Single Responsibility Principle (SRP) is for classes to do one thing and only have one reason to change. When building classes the more functionality you add in the more likely the class will need to change in the future unless you follow this principle.


What is a responsibility?

Class responsibilities are tied to the actors that call the class, so when the needs of the actors change that is when the class changes. For example say you have a Payroll class that can calculate salaries based on pay grade. That class has a salary responsibility. If there was also a method to persist a payroll run to a database we are now mixing responsibilities of calculating salaries and data persistence. We now have 2 responsibilities and 2 reasons to change.

Violating SRP

If we have more than one responsibility we are violating SRP. To solve this we can split out our data persistence code into another class and adhere to the Single Responsibility Principle. Another indicator of violating SRP is class fan out, having too many dependencies. In Java a high number of imports immediately indicates a high number of dependencies and most likely high complexity within the class itself.

Implementing SRP

So you've separated out you responsibilities and now you are left with a number of classes. One approach to grouping these classes would be to put them behind a Facade class so all access goes through the Facade. What if suddenly you needed to add reporting functionality? That would be a new class that the Facade could depend on. The Facade exposes a simple API but introduces this at the expense of coupling. Another approach is to invert the dependencies and create interfaces for each responsibility. This is another level of abstraction but ultimately your approach will depend on your requirements and how much engineering flexibility you need.