Remove the if-else hell
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…