Getting rid of a train of IF-ELSE

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() 

Exact syntax varies on language, but most of the popular languages have the ability to do it including Java, Python, PHP, C#, Javascript. So, you can indeed create method handlers and call them with all the arguments you need.

Example 2: Complex condition

We can have complex conditions and conditions with multiple variables. We can try to do two things:

  1. 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.
  2. 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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s