Skip to content
Advertisement

Replacing if else statement with pattern

I have a if else statement which might grow in the near future.

JavaScript

Since, this is already looking messy, I think it would be better if I can apply any design patterns here. I looked into Strategy pattern but I am not sure if that will reduce if else condition here. Any suggestions?

Advertisement

Answer

This is a classic Replace Condition dispatcher with Command in the Refactoring to Patterns book.

enter image description here

Basically you make a Command object for each of the blocks of code in your old if/else group and then make a Map of those commands where the keys are your condition Strings

JavaScript

Then instead of your if/else code it is instead:

JavaScript

Now if you need to later add new commands, you just add to the hash.

If you want to handle a default case, you can use the Null Object pattern to handle the case where a condition isn’t in the Map.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement