Categories
design-patterns

Ways to eliminate switch in code [closed]

192

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

5

  • 18

    Why would you want to eliminate switches, when used appropriately? Please can you elaborate on your question.

    – RB.

    Sep 24, 2008 at 10:37

  • I vote this question be made community editable because everybody is saying the same thing and it might be nice to consolidate all the opinions 😉

    – Josh

    Sep 24, 2008 at 10:50

  • 2

    Switch is not as standard as other instructions. For instance, in C++, you’re likely to forget the ‘break’ and then you’ll have unexpected results. Besides, this ‘break’ is too similar to a GOTO. I have never tried to eliminate switches, but for sure they’re not my favourite instruction. 😉

    – anon

    Sep 24, 2008 at 10:50

  • 2

    I think he’s referring to the switch concept and not the C++ or Java switch statement. A switch can also be a chain of ‘if-else if’ blocks.

    – Tim Frey

    Sep 24, 2008 at 14:16

  • 2

    You may be amused: there are a large number of notable programmers from the agile community joinng the anti-IF campaign: antiifcampaign.com/supporters.html

    – Mike A

    Nov 24, 2009 at 8:54

288

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

6

  • 2

    I being bashed because of similar suggestion in stackoverflow.com/questions/374239/… So many ppl don’t believe in polymorphism 🙂 Very good example.

    – Nazgob

    Dec 17, 2008 at 19:41

  • 38

    -1: I’ve never used a switch statement with typeof, and this answer doesn’t suggest ways or reasons to work around switch statements in other situations.

    – Kevin

    Jun 18, 2013 at 21:00

  • 3

    I agree with @Kevin – given example doesn’t really show how to eliminate switch by polymorphism. The simple examples: get name of enum by switching it’s values, or perform some code by appropriate values in some kind of algorithm.

    – HotJard

    Oct 13, 2013 at 7:35

  • I was wondering how to eliminate it before you can rely con specific implementations, i.e. in a factory. And I found a great example here stackoverflow.com/a/3434505/711855

    – juanmf

    Feb 19, 2016 at 23:27

  • 2

    very trivial example.

    – GuardianX

    Sep 18, 2016 at 1:42

261

See the Switch Statements Smell:

Typically, similar switch statements are scattered throughout a program. If you add or remove a clause in one switch, you often have to find and repair the others too.

Both Refactoring and Refactoring to Patterns have approaches to resolve this.

If your (pseudo) code looks like:

class RequestHandler {

    public void handleRequest(int action) {
        switch(action) {
            case LOGIN:
                doLogin();
                break;
            case LOGOUT:
                doLogout();
                break;
            case QUERY:
               doQuery();
               break;
        }
    }
}

This code violates the Open Closed Principle and is fragile to every new type of action code that comes along.
To remedy this you could introduce a ‘Command’ object:

interface Command {
    public void execute();
}

class LoginCommand implements Command {
    public void execute() {
        // do what doLogin() used to do
    }
}

class RequestHandler {
    private Map<Integer, Command> commandMap; // injected in, or obtained from a factory
    public void handleRequest(int action) {
        Command command = commandMap.get(action);
        command.execute();
    }
}

Hope this helps.

9

  • 7

    Thanks for the great example on how to refactor code. Though I might say in the beggining it is a little hard to read (because one has to switch between several files to completely understand it)

    – rshimoda

    Oct 29, 2008 at 23:51

  • 9

    The arguments against switch are valid as long as you realize that the polymorphic solution sacrifices code simplicity. In addition, if you always store your switch cases in enums, some compilers will warn you that states are missing from the switch.

    – Harvey

    Dec 22, 2008 at 18:32

  • 1

    This is a great example about complete/incomplete operations and of course re-structuring code into OOP. Thanks a ton. I think it will be useful if OOP / Design Patterns proponents suggest treating OOP concepts like operators rather than concepts. I mean that “extends”, “factory”, “implements”, etc are used so often across files, classes, branches. They should be simple as operators like “+”, “-“, “+=”, “?:”, “==”, “->” etc. When a programmer uses them in his mind as simply as operators, only then he can think across the full class library about program state and (in)complete operations.

    Jan 22, 2010 at 20:23

  • 18

    I am starting to think that SWITCH is much more understandable and logical, compared to this. And I usually like OOP very much, but this resolution seems too abstract for me

    May 10, 2015 at 14:58

  • 1

    With the Command object, would the code to generate Map<Integer, Command> not need a switch?

    – ataulm

    Jan 22, 2016 at 14:38


46

A switch is a pattern, whether implemented with a switch statement, if else chain, lookup table, oop polymorphism, pattern matching or something else.

Do you want to eliminate the use of the “switch statement” or the “switch pattern“? The first one can be eliminated, the second one, only if another pattern/algorithm can be used, and most of the time that is not possible or it’s not a better approach to do so.

If you want to eliminate the switch statement from code, the first question to ask is where does it make sense to eliminate the switch statement and use some other technique. Unfortunately the answer to this question is domain specific.

And remember that compilers can do various optimizations to switch statements. So for example if you want to do message processing efficiently, a switch statement is pretty much the way to go. But on the other hand running business rules based on a switch statement is probably not the best way to go and the application should be rearchitected.

Here are some alternatives to switch statement :

1

  • 1

    Could someone give a comparison of message processing using switch versus other alternatives?

    – Mike A

    Nov 24, 2009 at 8:53