What's The Best Alternative To An Out Of Control Switch Statement?
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:
Solution 3:
Three suggestions (echoing some already given):
- 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. 
- In an OO language, polymorphism might be the answer, as many have pointed out. 
- 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?"