Clean Code Tips 1: Use Top-Down Approach While Converting Complex Logic Into Methods
Should you use top-down approach or bottom-up for writing clean code? Here is the pitch for using top-down approach while converting complex logic into methods.
Join the DZone community and get the full member experience.Join For Free
To know how to write clean Method is the stepping stone of writing proper clean code. You already know common things like method should be clean, readable, giving proper names, so I will not write on this. I will focus on the flow of the method, and there are two ways to write a complex logic:
- Top-down approach
- Bottom-Up approach
For clean code, always choose the 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.
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.
Published at DZone with permission of Shamik Mitra, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.