Get Rid of If-else loop

Praveen G. Nair
Geek Culture
Published in
1 min readApr 10, 2022

--

In this blog we would see how can we get rid of multiple if-else comparison.

Replace if-else.

In many cases, we need to do multiple if-else conditions. Some developers prefer to use switch case, but even then it is not going to give clean and robust code. So in this blog we would see how to remove these multiple if-else conditions using Maps.

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

Given below is an example of multiple if-else condition.

if-else multiples.

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

We have to make sure our conditions fit with the map. Instead of writing logic handling for each case, We create a map and put the case and the logic as key, value pairs. Hence, we can retrieve the logic from the map based on the key.

Using Map for handling multiple logic.

Hope you have enjoyed this pattern. Stay connected with me for more programming patterns !!

--

--

Praveen G. Nair
Geek Culture

I am a Software Developer and a Technologist. Interested in all cool stuffs of software development, Machine Learning and Cloud. https://praveeng-nair.web.app/