2006
11.29

Why Can’t I Switch Around Strings?

So, this afternoon I’ve been cleaning up a couple of the servlets (for satistica) which handle the interaction between the user interface (JSPs) and the data model that the system relies on (Java classes/JDBC). Since there’s a lot of different, but similar (heh ;) actions that occur, like edit, create, move, update, delete, e.t.c. for several data types the servlets use separate internal private methods to handle the actual processing each action. The control of the request/response is passed on to the relevant method by the ‘doGet’ and ‘doPost’ methods based on a string ‘action’ in the request parameters.

All well and good, works fine and all that. But the method is 150 lines or so of ‘if’ and ‘else if’ statements based on the ‘action’ string. It just looks so, messy. It looks like just the sort of thing that the ’switch’ control structure is for. Unfortunately, in Java you can only ’switch’ around ints, so I’m stuck with my collection of else if statements. Why can’t you use switch on strings? Is there some technical reason why this is bad idea? Maybe once Java is open source changes like this might have a chance of being implemented..?

./un-rant ….

5 comments so far

Add Your Comment
  1. Not sure what to say, other than this: http://youtube.com/watch?v=fhlqY145tpU should cheer you up :)

  2. Dude…..lame…..

  3. In all seriousness: When I was doing some work in python, I was rather upset by its lack of switching and stumbled upon this site:

    http://simon.incutio.com/archive/2004/05/07/switch

    Simon details how to create switch functionality without a switch function – maybe it’s of help, maybe I’m waaay off on this one :)

  4. Well – there’s already a switch statement in Java – but you can only switch around ints (or types which can be cast to ints).

    I found that Elharo (the guy who wrote XOM) mentioned this when talking about things he would change in Java. At least I’m not the only one :)

  5. In C you can only switch on integer types, because I believe it’s implemented as a JMP instruction with a table, or something. *I* know what I’m trying to say, anyway :P

    In Java, strings are objects, so you’d need to have some special cunning thing to do it. If it was implemented as loads of isEqual() calls (or whatever it’s called… been too long) then it wouldn’t have any speed benefit over a chain of if/else if’s (the main reason to use switch in C). It could use some sort of tree search, but that would be tough to generalise to classes other than string.

    {
    option1 => sub { result1; },
    option2 => sub { result2; }.
    option3 => sub { result3; },
    }->{$inputvalue}->();

    That’s Perl; I think Jonny’s Python thing used basically the same method.