Ways to eliminate switch in code

Mariano picture Mariano · Sep 24, 2008 · Viewed 132.6k times · Source

What are the ways to eliminate the use of switch in code?

Answer

mlarsen picture mlarsen · Sep 24, 2008

Switch-statements are not an antipattern per se, but if you're coding object oriented you should consider if the use of a switch is better solved with polymorphism instead of using a switch statement.

With polymorphism, this:

foreach (var animal in zoo) {
    switch (typeof(animal)) {
        case "dog":
            echo animal.bark();
            break;

        case "cat":
            echo animal.meow();
            break;
    }
}

becomes this:

foreach (var animal in zoo) {
    echo animal.speak();
}