Get Rid of If-else loop
In this blog we would see how can we get rid of multiple if-else comparison.
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.
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.
Hope you have enjoyed this pattern. Stay connected with me for more programming patterns !!