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. 

Clean code Tips 2:: Use Top-down Approach While converting complex logic into Methods.

Javaonfly :: Cleancode


To know How to write clean Method, is the stepping stone of writing proper Clean code, your already know common things like method should be clean, readable, giving proper names, I will not write on this I will focus on the flow of the method, there are two ways to write a complex logic

 a. Top-down approach

 b. Bottom-Up approach, 

for clean code, always choose Top-down approach there are several advantages


 In a crux, your logic should be written as a hierarchy of methods, like an article, let’s say you are reading an article by the headline you can understand what is all about? after reading the first paragraph you will have a crisp understanding of the topic and if you want details then go the other paragraphs.

The same way your methods must be structured. The top-level method must say about the feature, if you go to the next level it will tell about the algorithm, lastly, it will give the implementation details. I like to compose complex logic as a Template method pattern. To know what is Bottom-up and Disadvantages/comparison with Top-down, stay tuned for the next Tip.


Example :: 


  public void displayEvenNumberFromInputSource(){

         

          List<Integer> numberList =  processInputSource();

          List<Integer> evenList = findEven(numberList)

          display(evenList);

     }


Few things to Notice::


displayEvenNumberFromInputSource(), is the top-level method, by reading the name, we can understand it will display even number from an Input source, if I gave the name displayEvenNumber it will not tell the whole story, by reading that one would think it will display even number but from where they get the list of numbers is not there, so the name is important to give accordingly do not think about the method name is too long, actually this is not bad rather Good for your fellow developers, they will thank you later.


Also above method contains the algorithm, the algorithm has three separate concerns and those concerns are abstracted from each other.


processInputSource abstracted the algorithm for fetching the list of numbers, it can be fetched from File, JSON, XML, Command line, but it was abstracted in processInputSource method.


findEven method abstracted the finding even number logic


and display method abstracted the display logic, it can be on Terminal, JSON, XML, Response whatever logic is abstracted in the display.


So, no concern overlaps each other, they have a logical boundary in terms of method, so no leaky abstraction.











Clean code Tips1:: Urge to put comments? refrain to do it.


While you are writing code, assume you are writing a novel and your fellow coders is a reader of your novel, so anytime you think you have to put comment that means something wrong, you cant express yourselves through code. A real clean code does not need comments.


I know it is provocative to put complex business logic in plain English to easily explain the logic,  or Jira id/bug Id as a future reference in the codebase, but with time, the codebase evolves, methods are refactored but we forgot to refactor comments and your comment will be out of sync and gives a wrong interpretation about the method/code/business logic, undoubtedly a code smell,  if you need to put bug id for future reference put as a commit message but avoid comments remember clean code is self-explanatory.

Effective Advice on Spring @Async : Final Part .


In my previous articles, I discussed the Spring Async concept and How to use it effectively. If you want to revisit,  below are the links, Also for new visitors I recommend,  please go through previous parts after reading this one.


Part 1::  How Spring Async work internally, and how to use wisely so it assigns a task to a new thread.
Part2::  How to handles Exception, If something goes wrong while executing a task.

In this part, we will discuss How Spring Async work with the web.
I am very excited to share an experience with you about Spring Async and HttpRequest, as an interesting incident happened in one of my projects, and I believe by sharing it I can save some valuable time of yours in future.
Let me try to depict the scenario in Crisp word, 
Objective: The  objective was to pass some information from UI  to a backend controller, which will do some work and eventually calls an async mail service for triggers a mail.
One of my Juniors did the following code(Try to replicate the code intention with below code snippet, not the actual code ), can you spot where the problem lies?
The Controller:: Which collect information from UI as a form  HTTP Servelet request, do some operation and pass it to async Mail service.
package com.example.demo; 

import javax.servlet.http.HttpServletRequest; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetController {

@Autowired
private AsyncMailTrigger greeter;
@RequestMapping(value = "/greet", method = RequestMethod.GET)
public String greet(HttpServletRequest request) throws Exception {
String name = request.getParameter("name");
greeter.asyncGreet(request);
System.out.println(Thread.currentThread() + " Says Name is " + name);
System.out.println(Thread.currentThread().getName() + " Hashcode" + request.hashCode());
return name;
}
}
The Async Mail Service, I marked it as @Component you can easily change it to @Service. Here I have one method called asyncGreet which takes the HttpRequest, fetch the information from there and say, trigger the mail(this part is omitted for simplicity). Notice I put a Thread.sleep() here for a purpose, I will discuss the same later.
package com.example.demo;


import java.util.Map; 
import javax.servlet.http.HttpServletRequest; 
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncMailTrigger {

@Async
public void asyncGreet(HttpServletRequest request) throws Exception {
System.out.println("Trigger mail in a New Thread :: "  + Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName() + " greets before sleep" + request.getParameter("name"));
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " greets" + request.getParameter("name"));
System.out.println(Thread.currentThread().getName() + " Hashcode" + request.hashCode());
} 

}

Now the main class
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class SpringAsyncWebApplication {

public static void main(String[] args) {
SpringApplication.run(SpringAsyncWebApplication.class, args);
}

}
If I run this program output will very similar to below
Thread[http-nio-8080-exec-1,5,main] Says Name is Shamik
http-nio-8080-exec-1 Hashcode 821691136
Trigger mail in a New Thread:: task-1
task-1 greets before sleep Shamik
task-1 greets null task-1 Hashcode 821691136

Pay attention to the output, the request has the information still before sleep but after that, it magically disappears? Strange isn't?  But It is the same request object hashcode proves the same.
What happened ? what is the reason behind the disappearance of the information from Request? That was happening to my junior, the mail recipients, recipients name disappear from the request and mail is not triggered.
Let's put Sherlock hats to investigate the problem.
It is a very common problem with the request, to understand the problem have a look, how a request lifecycle works.
The request is created by the servlet container right before the call to servlet service method, In Spring then request passes through dispatcher servlet, in the Dispatcher servlet identifies the controller by request mapping and calls the desired method in the controller, and when the request has been served, servlet container either delete the request object or reset the state of the request object. (This totally depends on the container implementation, actually it maintains a pool of request). However, I am not going to the deep dive how container maintains the request object. 
But keep one thing in mind once the request has been served and response is committed, container reset its state or destroy the request object. 
Now put Spring Async part into the consideration, What async did,  it picks one thread from the thread pool and assigns the task to it, In our case, we pass the request object to the async thread and in the asyncGreet method, we are trying to extract info directly from the request.
But as this is async our main thread (Controller part)  will be not waiting for this thread to complete, so it's print the statement and commits the response, and refresh the state of the request object.
Ironically we pass the request object directly to the async thread, still, the point where the response is not committed in the main thread, request holds the data, I explicitly put a sleep a statement  so in main thread response can be committed and refresh the request state, so after sleep we experience there is no data in the request, it vanishes, a great experiment to prove the incident.

What we will learn from this experiment?
Never pass Request object or any object related to Request/Response(headers), directly while using async you never know when your response will be committed and refresh the state If you do you will face an intermittent error.

What can be done?
If you need to pass a bunch of information from request create a value object and set the information and pass the value object to Spring Async, in this manner, you can create a concrete solution.
RequestVO Object
 package com.example.demo; 
public class RequestVO {

String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
} 

}
Async Mail service
 package com.example.demo;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncMailTrigger {

@Async
public void asyncGreet(RequestVO reqVO) throws Exception {
System.out.println("Trigger mail in a New Thread :: "  + Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName() + " greets before sleep" + reqVO.getName());
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " greets" + reqVO.getName());

} 

}
Greet Controller
package com.example.demo; 

import javax.servlet.http.HttpServletRequest; 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetController {

@Autowired
private AsyncMailTrigger greeter;
@RequestMapping(value = "/greet", method = RequestMethod.GET)
public String greet(HttpServletRequest request) throws Exception {
String name = request.getParameter("name");
RequestVO vo = new RequestVO();
vo.setName(name);
//greeter.asyncGreet(request);
greeter.asyncGreet(vo);
System.out.println(Thread.currentThread() + " Says Name is " + name);
System.out.println(Thread.currentThread().getName() + " Hashcode" + request.hashCode());
return name;
}
}
Output
Thread[http-nio-8080-exec-1,5,main] Says Name is Shamik
http-nio-8080-exec-1 Hashcode 1669579896
Trigger mail in a New Thread:: task-1
task-1 greets before sleep Shamik
task-1 greets Shamik

Conclusion: Hope you enjoyed the article If you have questions, please put your questions on the comment box.