Saturday, November 23, 2019

Clean Code Heuristic G23: Prefer Polymorphism to Switch


Most people use switch statements because it’s the obvious brute force solution, not because it’s the right solution for the situation. So this heuristic is here to remind us to consider polymorphism before using a switch.

The cases where functions are more volatile than types are relatively rare. So every switch statement should be suspect.

I use the following “ONE SWITCH” rule:  

There may be no more than one switch statement for a given type of selection. The cases in that switch statement must create polymorphic objects that take the place of other switch statements in the rest of the system.

https://moderatemisbehaviour.github.io/clean-code-smells-and-heuristics/#g23-prefer-polymorphism-to-if-else-or-switch-case

No comments:

Post a Comment