Search code examples
design-patternslanguage-agnostic

Eliminating `switch` statements


What are ways of eliminating the use of switch statements in code?


Solution

  • 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();
    }