Remove the if-else hell

Sivaram Rasathurai
Javarevisited
Published in
2 min readMar 24, 2022

In some cases, we need to do multiple if-else conditions like the above. Someone may prefer to go with a switch case, but it is not going to give clean and robust code.

So How can we remove these multiple if-else conditions?

We can do it with a map.

  • For the String literals, you can use the HashMap
  • If you have enums use EnumMap instead of HashMap.

Instead of going with if-else conditions, we are going with a map

Make sure your conditions fit with the map. Instead of writing logic handling for each case, We had a map, and we put the case and the logic as key, value pairs. Hence, We can retrieve the logic from the map based on the key.

Thanks, Hrishabh Purohit & Gamehostprogram for your responses.
Those responses made me rethink again on this article to define the boundaries where we can use this technique.

I started with if-else because most of us(devs) start with if-else. but it is actually a nice replacement for a switch case.
Also, I wanna say, I don’t recommend using this in simple logic-related switch cases since it will increase the complexity of code readability. I prefer the map method when the class’s main functionality implementation depends on the switch case (strategy pattern).

Other Coding articles and resources you may like

And, if you are not a Medium member then I highly recommend you to join Medium and read great stories like this from great authors on different field. You can join Medium here

--

--