God Class- The developers booby trap!!!


 We all know what is a dystopian world -- A world of Chaos or Injustice, for developer Antipattern, is the dystopian world but surprisingly willingly or unwillingly developers love to live in a dystopian world.


Jokes apart, but this is the ground reality for most of the Legacy or old projects, common experience for developers are they change in one place, it breaks in another place. This has happened due to three major factors.


  1. Tight coupling and complex codebase.

  2. Multiple God Objects are driving Business Logic.

  3. Inexperienced coder and tight timeline.



I have discussed enough on Tight coupling, SRP, KISS, Law of Demeter all these, these are the basic stuff must-have in the developer toolbox irrespective of experience.


Ironically we assume junior developers(Not all Juniors some are very good) may not have this knowledge, only Core Java knowledge is sufficient for them, and in the selection process we omit those questions or in their syllabus, we will not include them. Anyway, I am not going to discuss that this is a different topic and different countries have different selection processes or syllabus.


My take on coding is if from the beginning you do not know basic design principles, you can’t build a good code, which impacted other project members in long run, implementing a business logic according to acceptance criteria is just the tip of Iceberg, handling negative scenario and modularizing and packaging would be your main focus. 


In Agile for a 5 pointers development story(not counting QA), i like (2 + 1+1+1) split,  

2 for designing and packaging higher component(Top-down approach)

1 for Building logic,

1 for handling error handling

1 for Unit Testing.


If you are not maintaining design and packaging you will end up with multiple God objects, let discuss what do we mean by God Objects?


God Object/Monster Object :: 


In a simple term, God objects are something that is doing everything or knows about everything. That Uncle who pokes his nose in everywhere. 


Want to trace your project’s God objects footprint? Check your last two months' commit history and plot a graph and find out which are classes modified most.


You will observe a few classes will change often, those are your projects God Objects- who controlling your projects. In a classical word a Feature Envy class. 


I always wonder what makes God Objects?


so, I try to see the commit history of the God object and found one use case that in the first place a developer creates objects which hold few important business responsibilities, the intention was to create a Mediator type of object which has reference to multiple other important objects to reduce the coupling and accomplish more business logic with a small line of codes. To know how Mediator reduces coupling you can check the Mediator pattern.


Then over time developers are adding logic on top as this class acts as one shop for all. Blindly developers put logic there as it has already all-important objects references !!!!!.

it grows over time until you get a big escalation and your project managers mandate no one touch this class!!!! 


So, If we restrict ourselves in the first place we can reduce the probability of God Object, Once Mediator object grows it will turn into God objects-- A obvious booby trap, Once God Objects are created I think at that point in the Agile era refactoring a God object is very tough and should be avoided. 

On the contrary, during each sprint, at the end of the development phase you need to pay attention to Modularizing and refactoring your code a must-do activity in Sprint, to accomplish it, take a blanket story for all development work, Sprint goal is not to only focus on MVP also it needs to focus on Technical quality, but the second one is missing most of the cases, As, Business or Scrum Master doesn't want to give importance on code quality, peer review. I am open to hearing various perspectives on the strategy, 

How to maintain good code quality in Sprint?


 God objects are bad for your code, it's a booby trap which brings unwanted side effects. Often your Mediator Objects turned in into God object, Pay attention to Mediator Objects after each sprint and refactor it when necessary, Restricting it in the first place will be the best protection not to refactor after it turned into God Objects.

Clean Code:: Method Arguments must be crisp and Encapsulated.


 While writing methods, please pay close attention to the method arguments, This is the one area where the method assimilates the foreign body into its core body. Foreign material is always dangerous, you do not have any control over it, but as an owner of a method, you can put a defensive mechanism aka Validation. Or the Anti-corruption layer of your method.


So, the first tip.

  1. Always put validation on the input argument, you can use java annotations to do the validation.


Now, let's think about what we do in a method after receiving the inputs.


Most methods will do three things.


  1. It will act on the inputs:: so the method will receive the inputs and apply some business logic on them and get a result.


Example::


public void buildReport(String firstName, String lastName, String address, int age, char sex, String dept) {

//build the report

}


If you pay attention to this method we can derive one important thing, the input parameter passed here has associativity, what I meant to say, all input parameters are passed into the method for which reason? Simple, to create the report we need those data. Think logically, when you build a report it will focus on a segment or a context. The Business rule always works to accomplish a feature inside a domain. So if you build a report which needs the above arguments that means you are dealing with the data which are used together frequently because they are in the same domain and same context.


In some cases, I saw some methods which take data from multiple domains and aggregate it and give a view of overall functionality but those cases are less. Mostly a method works on a narrowed feature under a domain. 

Tip 2 :  if your arguments list is long that means you are breaching encapsulations, easily you can tie them under an object as those arguments are often changed or used together, then pass that wrapped object.


I can modify the above method cleaner way



public void buildReport(EmployeeReportContext employeeReportContext) {

//build the report

}



I tied related arguments in the EmployeeReportContext object and make it a Monadic function(A method which takes one argument)




2.  Methods will take decisions based on the arguments:: it will take the arguments and based on the arguments perform some algorithm or business rule to accomplish a feature.




public void serachEmployee(String firstName,String lastName, String latLong, ,Long deptId) {

//build the search query based on the inputs.

}



Again, we can see we are dealing with related input which can be encapsulated in an object.

Now on top of this, another observation is if we pass multiple arguments that means this method is responsible for multiple decision making but we know in SRP Pyramid on a particular level one method is responsible for one responsibility. So the method is breaking SRP, how we can solve this, just segregate out the decision/responsibility by extract method strategy.


I will break the methods into small chunks, in this way by extracting responsibility. Also, reduce the argument list and make each method a monadic Method.



public void searchEmployee(EmployeeSearchInput input) {

Address address = findAdressFromLatLong(input.getLatLong());

Department dept = finDeptbyID(input.getDeptId());

//TODO :: populateEmployeeSearchInput using address and dept

query = buildSearchquery(input);

result = executeSearch(query)



}



3. Holder methods:: These kinds of methods are edge methods that will take the arguments and pass those arguments to next-level methods.


Now first understand why we need this type of method? I like to call them Edge methods like edge service, while we are building an N-tier architecture often we need to pass a good amount of data to the next tier, now if you pass multiple arguments to the next level it will create coupling.


On the other hand, we also do not want to call next tier methods multiple times, then in a distributed system, it will create a Chatty communication where we need to pass multiple data over the network multiple times.


So it boils down to one principal question: how we can pass all data in one shot,on top of that we need to think about the future if I want to pass new data between tiers how to accommodate them because the holder method is a contract between two layers you can’t change method signature often !!!!



So passing multiple arguments in the holder methods is not a solution, as in the future you can change the signature.


So the best way to design this type of method is to create a coarse-grained object (DTO), and pass all data in one shot, or a Map like structure key is the property and value is the object, in both cases, you can easily extend them without breaching the contract.


Example:: The best example is the HTTPRequest object it carries data from UI to controller and servlet doPost and doGet is the holder method which takes the request, extracts parameters from it, and then passes to the next level.


Also, DTO (Data Transfer Object) is doing the same job.



Conclusion:: what we learned from the article?


We learned whatever the method type is, always encapsulate the inputs parameter, never pass multiple parameters in a method, it brings smell in different ways. 


Try to restrict method argument to null-- no foreign body, or one, maximum 3 but over than three is risky, needs to wrap them or need to extract the responsibility from the calling method.


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.