Refactoring Switch Statements – Is There Any Real Use?

refactoringswitch statement

I was reading this article and was wondering, do we get rid of all switch statements by replacing them with a Dictionary or a Factory so that there are no switch statements at all in my projects.

Something did not quite add up.

The question is, do switch statements have any real use or do we go ahead and replace them with either a dictionary or a factory method (in using a factory method, of course, there will be a minimum use of switch statements for creating the objects using the factory…but that is about it).

Best Answer

Both switch statements and polymorphism have their use. Note though that a third option exists too (in languages which support function pointers / lambdas, and higher-order functions): mapping the identifiers in question to handler functions. This is available in e.g. C which is not an OO language, and C# which is*, but not (yet) in Java which is OO too*.

In some procedural languages (having no polymorphism nor higher-order functions) switch / if-else statements were the only way to solve a class of problems. So many developers, having accustomed to this way of thinking, continued to use switch even in OO languages, where polymorphism is often a better solution. This is why it is often recommended to avoid / refactor switch statements in favour of polymorphism.

At any rate, the best solution is always case dependent. The question is: which option gives you cleaner, more concise, more maintainable code in the long run?

Switch statements can often grow unwieldy, having dozens of cases, making their maintenance hard. Since you have to keep them in a single function, that function can grow huge. If this is the case, you should consider refactoring towards a map based and/or polymorphic solution.

If the same switch starts to pop up in multiple places, polymorphism is probably the best option to unify all these cases and simplify code. Especially if more cases are expected to be added in the future; the more places you need to update each time, the more possibilities for errors. However, often the individual case handlers are so simple, or there are so many of them, or they are so interrelated, that refactoring them into a full polymorphic class hierarchy is overkill, or results in a lot of duplicated code and/or tangled, hard to maintain class hierarchy. In this case, it may be simpler to use functions / lambdas instead (if your language allows you).

However, if you have a switch in a single place, with only a few cases doing something simple, it may well be the best solution to leave it like it is.

*I use the term "OO" loosely here; I am not interested in conceptual debates over what is "real" or "pure" OO.