Remove that IF-ELSE ladder
As a developer, there are times when you write a long (i.e. 5 or more) list of IF-ELSE conditions. Many times the business requirement demands you to write such a construct.
Nothing wrong in writing this type of code. However, there is one problem — reading these long If-else conditions can be a daunting task. Sometimes the code in each condition can be about ~10 odd LoC which makes it hard to understand what happens in each IF. Another problem is maintainability. How do we ensure that making a change in one or more conditions will not cause cascading effect? If you have exhaustive tests around this code then you are fortunate. Otherwise there is a problem.
At best its good to avoid writing long if-else conditions. Sometimes I have seen switch-case being used as a replacement for if-else. But in the end its still another type of if-else. In some other cases, I see developers moving the code within IF to a separate method/class and then invoke it. But this still does not solve the original problem. So how do you replace this if-else ladder into a meaningful design?
This problem can be solved using Enums. To remove the If-else condition, its important to move the condition and its corresponding action to a separate construct which will be an enum.
E.g. Consider the original code as below
Now we start by creating a new Enum class, say- AlgorithmExecutor.java.
Then for each IF scenario we add individual values in enum with match() and execute() methods.
Move the condition in IF to the match() method and operations to execute() method.
Then we add a static method, say — getAlgorithmFromCondition() as shown below.
Add the match() and execute() as abstract method declarations.
That’s it ! You have successfully refactored the code to remove IF-ELSE.
You can now replace the original IF-ELSE by -
If you liked my article don’t forget to clap 2, 4, 8… :-)