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.











Post a Comment