Skip to content Skip to sidebar Skip to footer

What's The Best Alternative To An Out Of Control Switch Statement?

I have inherited a project that has some huge switch statement blocks, with some containing up to 20 cases. What is a good way to rewrite these?

Solution 1:

Why would you want to rewrite them in a different structure? If you really have 20 cases that have to be handled individually, a switch/case is the way to go. A big chain of if/then logic would be horrible to maintain.

Polymorphism is another option if you are using an object-oriented language. Each subclass would implement it's own functionality in the method.

Solution 2:

Polymorphism. But it may not be a trivial refactoring.

Some examples and refs:

Refactoring (Googe books)

Switch Statement code smell and Polymorphism

Refactoring switch-statements

Solution 3:

Three suggestions (echoing some already given):

  1. Maybe a switch isn't as bad as you think. It can be ugly if the case blocks are large. Shorten them by extracting the logic into methods.

  2. In an OO language, polymorphism might be the answer, as many have pointed out.

  3. In a functional language, like Javascript, write a function that returns the function you need to run for whatever input. That might use a switch statement itself, or it might use a lookup table.

Solution 4:

You could always use a lookup table.

Solution 5:

There's nothing wrong with having 20 cases in a switch statement. You can tidy the code by refactoring and, at the very least, move the case processing into methods/functions.

Post a Comment for "What's The Best Alternative To An Out Of Control Switch Statement?"