abolish the switch statement

1 Dec

I can’t explain how much I hate the switch statement. I often do everything and anything to avoid using it. I just think that it makes code very very ugly. Moreover, the amount of times I have seen people using it when they only have two cases, you just wouldn’t believe me! Let’s look at an example in Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
switch (n)
{
    case 0: 
       System.out.println("I'm zero");
       break;
    case 1:
    case 3:
    case 5:
       System.out.println("I'm odd");
       break;
    case 2:
    case 4:
       System.out.println("I'm even");
}

Surely no-one can tell me this actually looks “nice”? I mean coding is all about looking nice and neat after all. You can give the compiler something that looks like dog meat and it won’t give a shit as long as it’s valid syntax. Code is ALL about us humans reading it. The above is also a simple example and switch statement are normally way more complicated than this.

The normal argument for using a switch is that it looks better than loads of if-then-elses, which I completely agree with as that looks ugly as well. Also, with Java (and others) you can only switch on integer values which is the height of annoyance. Furthermore, there can’t be a single person that has not suffered the “forgetting the break” problem on a switch statement. For the record, my main bugbear is the extra indentation the switch forces on me along with the fact that scrolling all the cases is frequently a nightmare.

So what am I proposing? Well what I tend to use to solve both the ugliness problem and the lack of support for switching on stuff other than an integer is a HashMap. I’m sure some are screaming “Am I hearing this idot correctly”!

I really do think this looks particularly nice when used in code and can reduce a massive sprawing switch statement in a method to one simple call. So what does this entail. First lets assume that we have a method that takes a string as an argument and depending on the contents of this string we perform a specific operation – this is a particularly common task. Let say we have a class like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Operations {
    // Operation is an interface with the method do attached
    HashMap<String, Operation> mapper;
 
     public Operations() {
        mapper.put("eyeSurgery", new EyeSurgery());
        mapper.put("heartSurgery", new HeartSurgery());
        mapper.put("heartKeyHoleSurgery", new HeartSurgery());
       // etc
     }
 
     /**
      * Carries out an operation, which is dependant on the value of op
      * and returns a string containing the results of this operation.
      */
    public String do(OpContext op) {
        return mapper.get(op.toString()).run(op);
    }
}

Now surely the code in method do looks better than a switch statement would? Obviously in this case you couldn’t even use a switch statement in Java, but even if the type of the HashMap key was Integer, I still proclaim this looks better. OK, you have the extra setup cost but it’s got to be worth it and should run fast enough for most needs. It also opens up the possibility of “switching” on any object based type rather than just an integer – presuming a sensible hash function being declared for your object. Obviously this is a simple example but hopefully it illustrates what I’m try to put across.

I’m not sure if this was really obvious and everyone is doing this already. Hopefully someone will get something out of this. So, down with the switch statement, long live the hash map!

10 Responses to “abolish the switch statement”

  1. Big Peter December 7, 2008 at 8:14 pm #

    Whats all this then? they will have you on as one of those boffins on BBCS Tommorows World soon.Have you invented that time machine yet, thats what I am holding out for.Hope your well Gregg your old friend Peter…

  2. Gregg December 7, 2008 at 9:25 pm #

    Alas no time machine yet Peter ;-) . Sorry about the rise in boffinness from the murky days of my old journal where scathing comment and drama was all the range, maybe someday I will bring it back elsewhere. Anyway hope you are good, I’m hoping to get over to the US next summer (canny afford Oz!) so if I go out near you I will drop you an email.

  3. Peter December 10, 2008 at 12:02 am #

    Sounds good Gregg plenty of room for you to stay.Have a merry Christmas and a Happy New Year.

  4. Gregg December 12, 2008 at 11:26 pm #

    Thanks Peter, let’s hope the credit crunch does’nae bite ma bum too much and scupper ma plans. Merry Christmas and a Happy New Year as well.

  5. Raghavan alias Saravanan M December 18, 2008 at 6:44 pm #

    Hi there,

    That sounds pretty neat and I had been already game :). It more or less resembles the Factory Design Pattern and for sure its worth for the advantages we can think of!

    It might have had an overhead in prior to 1.5 versions of Java due to the absence of Auto boxing/unboxing though!

    Cheers,
    Raghavan alias Saravanan M.

  6. Donal December 23, 2008 at 4:52 am #

    One example of where a switch statement is pretier than an if-else is when switching on enums. In fact, I would argue that in code such as that shown above, you should be using an enum, rather than a String, because of the extra type safety.

    What makes a switch statement nicer than an if statement when branching based on an enum is that don’t have to (in fact you can’t) include the name of the enum in each branch.

  7. Gregg December 23, 2008 at 11:27 am #

    Hi Donal, thanks for reading.

    If you are given a string though you still have to create an enum at some point probably using a switch, if statement, or via the method in my post based on the string you have been given. No? I should say though that I’m not saying an if statement is much better, hence why I proposed doing away with both as per my example.

Trackbacks and Pingbacks

  1. 7 ways to write beautiful code « Kata learns to code - December 5, 2008

    [...] is by no means an exhaustive list and I could have gone on longer – in fact my abolish the switch statement motto would have been number 8 if I had not already mentioned it before. However, it has to end [...]

  2. Nice code and switches « NRGsoft - January 10, 2012

    [...] I had a thought while I was working on the game Alone In the Office (my LudumDare 22 entry). I wonder if I can make this code look more beautiful. So I went through and refactored the code. Okay, so I cleaned it up. There was cleaning to be done. But, I wondered if I could find any useful tid-bits of information about what other people do to keep code nice. I found this article and I noticed B. B is to return the immediate value of a boolean test instead of testing if the boolean test returned true or false. Mind you, in certain cases you DO need to check. In the cases of some of my code, I did not. B is the one thing I apparently overlooked in programming over the years. It’s interesting how I never noticed it to say the least. Anyways, upon reading to the end I find this article. [...]

  3. 7 ways to write beautiful code | Web development - November 21, 2012

    [...] is by no means an exhaustive list and I could have gone on longer – in fact my abolish the switch statement motto would have been number 8 if I had not already mentioned it before. However, it has to end [...]

Leave a Reply