Clean code Tip : SRP is the MEDUSA of Clean code family.

While we are hearing tips on Clean code, the most common tip is maintaining SRP while writing class or methods, in a broader scope Module/Package/Service/API.

But Irony is, SRP is the most powerful but obscured principle in the Design toolbox, this throws a web of confusion and you are stoned by thinking should I use it in the right way or not? That's why I like to call SRP Medusa. Most of the time it succumbs us and we are ending up with anti-KISS code but If we use it in the right proportion, then we can create a cohesive and robust architecture.


It is time to quickly recap the definition of SRP.


“The single-responsibility principle (SRP) is a computer-programming principle that states that every module, class, or function in a computer program should have responsibility over a single part of that program's functionality, which it should encapsulate. All of that module, class, or function's services should be narrowly aligned with that responsibility.”


Let’s demystify the Confusions

  1. What does it mean by SIngle responsibility?

  2. How to define a single responsibility in the Class/Orchestrator method./Package level?

  1. How SRP can be maintained in method level/ Class level/Service level/, isn't it contradictory? If a module/Service maintains SRP then what multiple Classes/methods inside it maintains?


1. What does it mean by SIngle responsibility?

 According to Robert C Martin, Single responsibility means each component has one reason to change, if you have to modify the component for multiple reasons then it breaks SRP. but the question is, what does it mean by reason, how do I find the reason? How can we restrict components to serve just one reason?

let me take an example code snippet to discuss it more, I keep this example confined to the method level.


public void displayEvenNumberfromInput(){

List <Integer> numberList = CommandLine.getNumberInputAsList();

List<Integer> evenList = new ArrayList<Integer>();

for(Integer number : numberList){

if(number %2 ==0){

evenList.add(number);

}

}

System.out.println(“Even List :: ” + evenList );

}

Now read the method carefully and ask yourself, in which reason, you have to edit the method, those will be the reason and we need to separate them out by wrapping by a class/method according to the needs.

The above example invoked a method on an associated class called CommandLIne, but think If requirement changes and we do not want to read from Command line but from JSON, so you have to modify your code. So this is one reason to change.

If I want to change the algorithm, then also I need to change the method, so this is the second reason to change.

At last, rather than print in the console If I want to save the output in File so, this is another reason for the change.

So, I can see the above method has three reasons to change, a small method but doing so much.


2. How to define a single responsibility in the Class/Orchestrator method/Package level?

Take away from the above paragraph is, by asking questions finding the reason for the change. If you are new I would suggest writing a method then checking for the algorithm steps, extracting out the non-related steps, do not separate related step to achieve granular level SRP, it will create Code smell and increase coupling, 

Now for architecting service or class study the acceptance criteria and encapsulate non-related acceptance criteria.

Another approach is trying to find out commit which classes are often committed together pay a closer look at them any find dependency you can extract out from them, or in a class change the field name and found what are the methods gives you the error, probably they are very related and closed, so avoid to segregate them in a separate class, again these are just strategy but to use SRP in the right proportion, not making code too granular, maintaining KISS and achieving cohesion need well-versed knowledge in the domain, and architecting.

 sometime you will see some methods/Class are breaking SRP but if you pay closer look reasons are strangled together so no need to separate them out it will increase the overhead of maintainability cost,

Example::  Like if the minimum balance is over some amount then do the debit operation, here validation and debit operation are linked together so let it be in the same class.


So, domain knowledge and what context you are writing the class/methods is important, initially while architecting a class/module may be wrong in the long run but next time when you need to touch the component try to understand why you need to touch that component and separate out that concern. So Refactor is a must - to get a proper SRP, you have to do multiple refactoring, so take time, take a buffer in your story point. Refactor is a first-class citizen while you doing code


Let see How we can curb out the responsibility from the last example?


  public void displayEvenNumberFromInputSource(){         

          List<Integer> numberList = processFactory. processInputSource();

          List<Integer> evenList = algoFactory.findEven(numberList)

          displayable.display(evenList);

     }

Now I abstract the three reasons and separate them out into different classes, I am assuming there are multiple Inputs Source we need to support so I separated it into a different class, If that is not the case only we have to read from the command line, I will separate them in a separate method in Same class, Now the hardest question comes, you may say my class breaks SRP as it handles three concerns even the orchestrator method displayEvenNumberFromInputSource handling three separate concerns so sure breach of SRP.

With this context, I will dive deep into the most obscured part of SRP.


3. How SRP can be maintained in method level/ Class level/Service level/, isn't it contradictory? If a module/Service maintains SRP then what responsibility Classes/methods maintain?

I personally think, there is one part missing in SRP definition, the term hierarchy/Level, SRP does not make sense if you apply it to a specific point it is a range.


It is like a Pyramid, like our Food chain Pyramid. In a particular domain space if we visualize it using a bottom-up approach, it is starting from method level then responsibility merging in Orchestrator method, then Class, then package, then service/module level. It goes from more specialization to generalization in an upward direction.


So, in a top-level, it will do one responsibility which consists of multiple sub responsibilities, and each level of the SRP pyramid delegates the responsibility to the next level and it is continuously going on until it reaches the bottom level until each method handles a single responsibility.

But at the same level of the SRP pyramid, no component will perform more than one responsibility of that particular level. Each component level must not cross each other then it is breaching the SRP pyramid level and your higher-order component will know the lower order components, so against the Dependency Inversion principle. Only the upper-level talks to the next level through encapsulation.


Think about the HR department, what is its job in the organization -- managing Human resource, In an organization This is one of the SRP Pyramid Tower, Payroll, Finance are the different SRP Pyramid Towers. Each tower talks to the other tower through an Organization in-house API contract and each tower specifically handles one broad responsibility of that organization.


Now if we deep down to HR SRP Pyramid, next level we can have multiple sub responsibilities like managing different geography, different policies, so each time you deep down to SRP Pyramid you are dividing the responsibilities to sub responsibilities and give it to a more specific component to do that job.


That is the main essence of SRP, Divide, and conquer the work.

In SRP Pyramid, You can not compare top-level component with bottom level and then thinking top-level component is breaking SRP, you are then comparing Apple with Oranges.





So I would like to rephrase the definition of SRP.

“The single-responsibility principle (SRP) is a computer-programming principle that states that SRP starts with a SRP Pyramid , where a module, class or function in a computer program placed in a level and in that level they have responsibility over a single part of that program's functionality, which it should encapsulate from the next level . All of that module, class or function's services should be narrowly aligned with that responsibility.”


Or in a simple 


In SRP Pyramid each component in a Level has one reason to change. 

Design thoughts on Open/Close Principle

Open close principle


According to Bertrand Meyer
 “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

Read it the first time one can think the definition is a bit abstract as design principals are.
But the aforesaid statement is very powerful and can save you from fragile design and wired bugs.

The statement says that Design should be done such a way so it can welcome new changes
but without tampering the old implementation. Because your old implementation is tested and run fine in production, to welcome new changes it is not good to break old ones. So this principal says welcome new changes on top of old changes.

Let take an example, suppose requirement is to create a class which determines the area of a Rectangle.

This is very easy to develop for an OO Developer

Initial code like
package com.example.openclose;

public class AreaBuilder {
      
       public void calculateRectangleArea(int length,int breadth)
       {
              System.out.println("Area of Rectangle is " + length*breadth);
       }
      
       public static void main(String[] args) {
             
              AreaBuilder builder = new AreaBuilder();
              builder.calculateRectangleArea(20, 10);
             
             
       }

}

The code is tested and then deployed.  But after some day new feature request raise now this class should able to compute the area of the square also.

Inexperienced developer will incorporate the requirements in following way

package com.example.openclose;

public class AreaBuilder {
      
       private void calculateRectangleArea(int length,int breadth)
       {
              System.out.println("Area of Rectangle is " + length*breadth);
       }
      
      
       private void calculateSquareArea(int length)
       {
              System.out.println("Area of Square is " + length*length);
       }
      
       public void getArea(String type,int length,int breadth)
       {
              if("square".equalsIgnoreCase(type))
              {
                     calculateSquareArea(length);
              }
              else if("rectangle".equalsIgnoreCase(type))
              {
                     calculateRectangleArea(length,breadth);
              }
       }
       public void getArea(String type,int length)
       {
              getArea(type,length,length);
       }

      
      
      
       public static void main(String[] args) {
             
              AreaBuilder builder = new AreaBuilder();
              //builder.calculateRectangleArea(20, 10);
              builder.getArea("square", 10);
              builder.getArea("rectangle", 10,5);
             
             
       }

}

Certainly, it will meet the requirements but break the Open close principal. Also, this code has some shortcomings

1.    To incorporate new changes, we will modify the old class so it breaks the statement “closed for modification”.
2.    The new code can break old functionality if the implementation is wrong, so we not only fail to deliver new code but also break the old functionality which is not intended.
3.    For every new shape added in the system, we need to modify this class and make the class more complex and less cohesive.

To overcome aforesaid problems, we try to follow the principal refactor the code.

“Open for extension closed for modification”
In java, the extension can achieve through inheritance. So we can create an interface called “shape” and a method called area() in it so every shape can implement area method and provide its implementation.
So if a new shape is coming we just create a new class and implement shape interface if anything goes wrong only that shape class will be impacted not the previous implementations thats why the Open close principal is so important in design.

Refactor code:
package com.example.openclose;

public interface shape {
      
       public void area();

}

package com.example.openclose;

public class Rectangle implements shape{
       private int length;
       private int breadth;
       Rectangle(int length,int breadth)
       {
              this.length=length;
              this.breadth=breadth;
       }

       @Override
       public void area() {
              System.out.println("Area of Rectangle is " + length*breadth);
             
       }

}

package com.example.openclose;

public class Square implements shape{

       private int edge;
       public Square(int edge)
       {
              this.edge=edge;
       }
       @Override
       public void area() {
              System.out.println("Area of Square is " + edge*edge);
             
       }

}

package com.example.openclose;

public class ShapeManager {
      
       private static ShapeManager manager = new ShapeManager();
      
       shape shape;
      
       private ShapeManager()
       {
             
       }
      
       public static ShapeManager getInstance()
       {
              return manager;
       }
      
      
       public void getArea() throws IllegalArgumentException
       {
              if(shape ==null)
              {
                     throw new IllegalArgumentException("please provide a Shape");
              }
              shape.area();
       }
      
      
       public shape getShape() {
              return shape;
       }



       public void setShape(shape shape) {
              this.shape = shape;
       }



       public static void main(String[] args) {
             
              shape rect = new Rectangle(10,20);
              shape square = new Square(10);
             
              ShapeManager instance = ShapeManager.getInstance();
              instance.setShape(rect);
              instance.getArea();
             
              instance.setShape(square);
              instance.getArea();
             
             
       }

}

Output :

 Area of Rectangle is 200
Area of Square is 100


Hooray, we refactor the code and it is maintaining the principal. We can incorporate any number of shape by adding new classes and without modifying the old classes.

The client is happy now they want to introduce a brand new feature Now shape can be drawn on a paper.
So inexperinced developer thought it is easy task to do just add a new method call drawShape() on shape interface it will meet client needs and not breaking the Open Close principle
Let’s do that,

package com.example.openclose;

public interface shape {
      
       public void area();
      
       public void drawShape();

}

package com.example.openclose;

public class Rectangle implements shape{
       private int length;
       private int breadth;
       Rectangle(int length,int breadth)
       {
              this.length=length;
              this.breadth=breadth;
       }

       @Override
       public void area() {
              System.out.println("Area of Rectangle is " + length*breadth);
             
       }

       @Override
       public void drawShape() {
             
              System.out.println("drawing recangle on paper" );
             
       }

}
 package com.example.openclose;

public class Square implements shape{

       private int edge;
       public Square(int edge)
       {
              this.edge=edge;
       }
       @Override
       public void area() {
              System.out.println("Area of Square is " + edge*edge);
             
       }
       @Override
       public void drawShape() {
              System.out.println("drawing square on paper" );
             
       }

}

package com.example.openclose;

public class ShapeManager {
      
       private static ShapeManager manager = new ShapeManager();
      
       shape shape;
      
       private ShapeManager()
       {
             
       }
      
       public static ShapeManager getInstance()
       {
              return manager;
       }
      
      
       public void getArea() throws IllegalArgumentException
       {
              if(shape ==null)
              {
                     throw new IllegalArgumentException("please provide a Shape");
              }
              shape.area();
       }
      
       public void draw() throws IllegalArgumentException
       {
              if(shape ==null)
              {
                     throw new IllegalArgumentException("please provide a Shape");
              }
              shape.drawShape();
       }
      
      
       public shape getShape() {
              return shape;
       }



       public void setShape(shape shape) {
              this.shape = shape;
       }



       public static void main(String[] args) {
             
              shape rect = new Rectangle(10,20);
              shape square = new Square(10);
             
              ShapeManager instance = ShapeManager.getInstance();
              instance.setShape(rect);
              instance.getArea();
              instance.draw();
             
              instance.setShape(square);
              instance.getArea();
              instance.draw();
             
             
       }

}

Output :
Area of Rectangle is 200
drawing recangle on paper
Area of Square is 100
drawing square on paper

So far so good. But is it really maintains Open/close principle? In bare eyes, yes but if we put our thinking cap, there is clue in client needs which can break this principal
Clients want shape can be drawn on a paper but it can be drawn on Computer or in canvas also.

So in future, if clients want to draw on the computer. To incorporate this change Open close principal will be broken. As again we need to put if /else check on each shape drawshape() method.



Now we will discuss How judiciously we can design open close principle?
1.    I classified Objects properties in two ways a. primary properties b. Composition properties.
2.    If any functionality(method) depends on only primary properties i.e which are the sole properties of that domain object.  You can declare them in the interface or abstract class from which this class inherited.
3.    If a functionality depends on an external entity always use composition rather than inheritance. (Here draw functionality depends on paper an external entity so we should use composition rather than inheritance)

Now refactor the code again to support draw function.
package com.example.openclose;

public interface shape {
      
       public void area();
      
       public void drawShape();

}

package com.example.openclose;

public interface drawAPI {
      
       public String draw();

}

package com.example.openclose;

public class PaperDraw implements drawAPI{

       @Override
       public String draw() {
              return "paper";
             
       }

}

package com.example.openclose;

public class ComputerDraw implements drawAPI{

       @Override
       public String draw() {
              // TODO Auto-generated method stub
              return "computer";
       }

}

package com.example.openclose;

public class Rectangle implements shape{
       private int length;
       private int breadth;
       drawAPI api;
       Rectangle(int length,int breadth,drawAPI api)
       {
              this.length=length;
              this.breadth=breadth;
              this.api=api;
       }

       @Override
       public void area() {
              System.out.println("Area of Rectangle is " + length*breadth);
             
       }

       @Override
       public void drawShape() {
             
              String medium = api.draw();
              System.out.println("drawing recangle on " + medium);
             
       }

      

}

package com.example.openclose;

public class Square implements shape{

       private int edge;
       drawAPI api;
       public Square(int edge,drawAPI api)
       {
              this.edge=edge;
              this.api=api;
       }
       @Override
       public void area() {
              System.out.println("Area of Square is " + edge*edge);
             
       }
       @Override
       public void drawShape() {
              String medium=api.draw();
              System.out.println("drawing square on "+medium );
             
       }

}

package com.example.openclose;

public class ShapeManager {
      
       private static ShapeManager manager = new ShapeManager();
      
       shape shape;
      
       private ShapeManager()
       {
             
       }
      
       public static ShapeManager getInstance()
       {
              return manager;
       }
      
      
       public void getArea() throws IllegalArgumentException
       {
              if(shape ==null)
              {
                     throw new IllegalArgumentException("please provide a Shape");
              }
              shape.area();
       }
      
       public void draw() throws IllegalArgumentException
       {
              if(shape ==null)
              {
                     throw new IllegalArgumentException("please provide a Shape");
              }
              shape.drawShape();
       }
      
      
       public shape getShape() {
              return shape;
       }



       public void setShape(shape shape) {
              this.shape = shape;
       }



       public static void main(String[] args) {
             
              shape rect = new Rectangle(10,20,new ComputerDraw());
              shape square = new Square(10,new PaperDraw());
             
              ShapeManager instance = ShapeManager.getInstance();
              instance.setShape(rect);
              instance.getArea();
              instance.draw();
             
              instance.setShape(square);
              instance.getArea();
              instance.draw();
             
             
       }

}

Output :
Area of Rectangle is 200
drawing rectangle on computer
Area of Square is 100
drawing square on paper


Now draw() method is in shape class as we assume every shape is drawable and we create  composition between  shape family and drawAPI family.

But to maintain Open close principal we need to create a lot of classes. Make code complex.
I throw an open question,

 If a client is reluctant for change or development time is short or for a system where change requests are very less, then should we always maintain open/close principle or break that rule and make the code much simpler?