How to remove large if-else-if chain [duplicate]

You can extract the code in each branch to a separate method, then turn the methods into implementations of a common base interface (let’s call it Handler). After that, you can fill a Map<String, Handler> and just look up and execute the right handler for given string.

Unfortunately the implementation of 100+ subclasses for the interface requires quite a lot of boilerplate code, but currently there is no simpler way in Java to achieve this. Implementing the cases as elements of an Enum may help somewhat – here is an example. The ideal solution would be using closures / lambdas, but alas we have to wait till Java 8 for that…

Leave a Comment