It is rare but probably happens once in a few years that we write a very long list of if-else blocks. Not only this kind of code is hard to manage, it is bad for a single responsibility. And it’s slow. I just devised a faster and cleaner way to do it.
Example 1: Simple condition
Say, I am writing a reward system for a sport and have a variable “position”. Based on the position I will execute different reward algorithms. This is an over-simplification. In actual cases, the reward methods might be completely different ones, and you can’t use a “for loop”. There can be 10 positions. So, my initial code looks like:
if ( position == 1 ) getReward1(); else if ( position == 2 ) getReward2(); else if ( position == 3 ) getReward3(); else if ( position == 4 ) getReward4(); else if ( position == 5 ) getReward5(); else if ( position == 6 ) getReward6(); else if ( position == 7 ) getReward7(); else if ( position == 8 ) getReward8(); else if ( position == 9 ) getReward9(); else if ( position == 10 ) getReward10();
Now I can I make this code clean?
First, I create a map with position and method handler
Map<Integer, MethodInterface> handles;
Then I just invoke the method somewhat like this handles.get(position).invoke()
Example 2: Complex condition
We can have complex conditions and conditions with multiple variables. We can try to do two things:
- Enumerate all the possible values, concatenate the values into strings, and create hashmap like before. It may occupy some memory, still, the code is clean and execution is fast.
- You can convert continuous values into discrete labels and do that job. But this can be an overkill.
Remember that you will only need to manipulate the hashmap to modify the code! So, if the modification gets complex, you should avoid this process. But if the modification is easy, you should follow this.