Switch Statements
Signs and Symptoms
You have a complex switch
operator or sequence of if
statements.
As a rule of thumb, when you see switch
you should think of polymorphism.
Treatment
- To isolate
switch
and put it in the right class, you may need Extract Method and then Move Method. - If a
switch
is based on type code, such as when the program’s runtime mode is switched, use Replace Type Code With Subclasses or Strategy - After specifying the inheritance structure, use Replace Conditional With Polymorphism
- If there aren’t too many conditions in the operator and they all call same method with different parameters, polymorphism will be superfluous. If this case, you can break that method into multiple smaller methods with Replace Parameter With Explicit Methods and change the
switch
accordingly. - If one of the conditional options is
null
, use introduce-null-object.
Payoff
- Improved code organization.