SOLID- Single Responsibility Principle


“A class should have only one reason to change.”  Robert C. Martin

Example,
Consider a module that compiles and prints a report.
Such a module can be changed for two reasons.
  • The content of the report could change.
  • The format of the report could change.


The single responsibility principle says that these two aspects of the problem are really two separate responsibilities, and therefore be in separate classes or modules.


It would be a bad design to couple two things that change for different reasons at different times.


One responsibility doesn't mean that the class has only ONE method. A responsibility can be implemented by means of different methods in the class.


Benefits:
  • Coupling reduced.
  • Code easier to understand and maintain.


Example in java


Before:-
public class GenerateReport
{
 public void printReport(JsonObject object)
 {
 
      //print report
   
 }
 public JSONObject getContent(User user)
 {
 
   //Generate content.
   
 }
}




After:-
public class PrintReport
{
 public void printReport(JsonObject object)
 {
 
      //print report
   
 }
 
}

public class GenerateContent{
 public JSONObject getContent(User user)
 {
 
   //Generate content.
   
 }
}


What needs to have single responsibility?
Each part of the system.
  • The methods
  • The classes
  • The packages
  • The modules

How to Recognize a Break of the SRP?
  • Class Has too Many Dependencies
    • A constructor with too many input parameters implies many dependencies (hopefully you do inject dependencies).  
    • If you need to mock too many objects, it usually means breaking the SRP.
  • Method Has Too Many Parameters
  • The Test Class Becomes Too Complicated
    • If the test has too many variants, it might suggest that the class has too many responsibilities.
    • It might suggest that some methods do too much.
  • Class / Method is Long
  • Class With Low Cohesion



Comments