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.
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
7 Best Courses to Learn Refactoring and Improve Coding Skills in Java
My favorite online courses to learn refactoring and best practices to improve your coding skills and become a better…
Clean Code Review — A must-read Coding Book for Programmers
Want to learn the art of converting a bad code to good code? This book can help
Top 6 Courses to Learn Code Refactoring for Experienced Java Programmers
Hello guys, if you want to improve your coding skills, learn to refactor and other coding best practices, and look for…
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