Strings in switch statements

Apparently, with JDK 7 we will have Strings in switch statements. I got a SCPJ certification long time back, but if someone asks me to write a switch statement in a job interview today, I could probably fail: I begun writing Java code in 2000, and I bet I used switch statement six or seven times since then. Half of that times at the beginning for sure, and probably always I should have avoided that in favor of making better object oriented design.

Bad programmer have been able to use Strings in switch statements since the beginning: necessity sharpen sb's wits.

I found a nice pearl regarding the switch on the Strings. Viewer Discretion is Advised!
Look at this:

 1switch(_Temp.getLocalName().toLowerCase().hashCode())
 2{
 3  case -84691548:  // = "get-transfer-url".toLowerCase().hashCode()
 4  {
 5    _getTransferUrl =  _Temp.getFirstChild().getNodeValue().trim() ;
 6    break;
 7  }
 8  case 457922078:  // = "is-authorized".toLowerCase().hashCode()
 9  {
10    _isAuthorized = Boolean.valueOf( _Temp.getFirstChild().getNodeValue().trim() ).booleanValue();
11    break;
12  }
13  case 998201997:  // = "is-charged".toLowerCase().hashCode()
14  {
15    _isCharged = Boolean.valueOf( _Temp.getFirstChild().getNodeValue().trim() ).booleanValue();
16    break;
17  }
18  case -2085709659:  // = "get-resource".toLowerCase().hashCode()
19  {
20    _getResource = new ChargingResource(_Temp);
21    break;
22  }
23  //... continues for about 500 lines more...
24} 

Hoping Java will never change the hash code implementation on the Strings, as actually happened before for other wrapper classes.
At least the author could have used the string itself in place of the comment... I imagine the programmer hard coding the hash code in the switch to boost performance. Very smart...

1switch(_Temp.getLocalName().toLowerCase().hashCode())
2{
3  case "get-transfer-url".toLowerCase().hashCode() :
4  {
5    _getTransferUrl =  _Temp.getFirstChild().getNodeValue().trim() ;
6    break;
7  }
8
9} 

Still horrible, and designed to fail (hash codes can conflict).

Maybe I am beginning to become a conservative dinosaur, but since JDK 5 (and maybe 1.4) I don't see the reason of many of the "improvements" that have been included and will be included in the Java language. Simplicity made of Java a success. I see every day pile of code written by "experienced" developers capable to overpatternize banalities and still unable to handle properly an exception. What's the matter of adding more complexity and features? Also including harmful ones like String in switch statement... Personally I think that the switch statement should be deprecated tout cour.


11 Responses to “Strings in switch statements”  

  1. 1 raveman

    I use switch for ints and i think switch for string is a good idea, because it looks better then if else if else if else if else if else if else. however i dont care if they add it to java, the idea is so old that i find it hard to care. the problem with switch is that it ends with break and some c people will go crazy with it and dont add break sometimes.

  2. 2 Luigi
  3. 3 wentman

    The purpose of the switch statement is more for j2me. Switching uses a jump table, so only 2 comparisons is needed for any switch, whereas a if else if else if is many comparisons and therefore much slower. For j2se and j2ee, it is bad form unless you really need the performance boost, but in that case(yes the pun is intended), you should move to c .

  4. 4 Daniel

    I think the current fashion of pushing all kinds of features in Java is a mistake. Only because language X managed to cram more features in the language is not going to make language X more successful. Unfortunately damage has been done already. Because features were pushed in and they were half-baked. Like the “foreach” statement which can be used only for read but not for change. Line the “erased” generics and so on. Personally I don’t care if I have to type a bit more if things are clear. Yes Java is a more verbose language than some others. But for the kind of success Java seeks this is not important. The typing is such a small part of the development.

  5. 5 Vladimir Tsukur

    I agree with Luigi, and NEVER use switch because there is always a possibility to replace such code smell with if or Map based implementation (last option is much better).

  6. 6 Tony

    Switch is only for J2ME…is bad form in J2SE? Are you kidding? There’s absolutely nothing wrong with using switch blocks in any code, especially if using enums, which were made to work within a switch block. I’d say switching to another language, rather than first attempting to optimize your own code is bad form.

  7. 7 Ishaaq

    Hmm, maybe you’re right – you are becoming a dinosaur.

    “Blub falls right in the middle of the abstractness continuum… As long as our hypothetical Blub programmer is looking down the power continuum, he knows he’s looking down. Languages less powerful than Blub are obviously less powerful, because they’re missing some feature he’s used to. But when our hypothetical Blub programmer looks in the other direction, up the power continuum, he doesn’t realize he’s looking up. What he sees are merely weird languages… Blub is good enough for him, because he thinks in Blub.” — Paul Graham, Beating the Averages

  8. 8 Luigi

    I think patterns should be used carefully, but notice that many of them can be used to replace smelling switch or if-else-if-else statements to implement a common behavior:

    chain of responsibility. for instance jdbc: you don’t switch on the proper jdbc driver when you specify an url to the driver manager.

    command pattern. for instance struts: you have a list of configured commands attached to a discriminator url. This avoid hard coding command triggers to switching on command implementations.

    strategy: you have a list of algorithms that are injected in the executors, instead of having a switch in the executor to select the appropriate algorithm

    observer: you have a set of classes that handle specific messages, instead of having a single class that switch on the messages to notify the appropriate listeners

    If switch is perfect, it is quite strange that people invented so many patterns to avoid that (in different contexts, and for solving different problems). :)

    I agree that sometime if-else-if-else are simpler than overcomplicated solutions. But most of the time doing a good design avoids switches and repeated ifs. My opinion is that is best to go for the easiest code.

  9. 9 Ishaaq

    Ok, I am going to make a bold claim – only because sometimes you have to make an extreme statement to make a point: a number of “design patterns” are useless in a functional language.

    The switch case construct and the foreach construct that another of the posters above disliked so much are used extensively by functional language proponents for a variety of tasks that make generally accepted design patterns redundant and seem more cumbersome once you get used to its strange looking syntax.

    Remember that design patterns are not something sacred – they are simply common coding patterns to solve common problems – quite often these patterns are developed from within the context of the limitations of a language – it is a common misconception that design patterns are language agnostic – this is not true. Thankfully, this is not an original thought on my part – I have references to back me up, off the cuff here’s one.

    As for the switch case itself – to see how it and its more advanced functional brother: pattern matching are used extensively and quite usefully you’ll need to look at functional language implementations – the topic is too complex for me to explain in a short reply here, suffice to say that once you get used to functional programming you’ll find yourself frustrated with non-functional programming languages. Since you’re obviously coming from a Java background I’d suggest you start with Scala – it takes a happy medium between OO and functional paradigms and even runs in the JVM and is interoperable with Java.

    My earlier comment with Paul Graham’s fictitious “Blub” programming language was not in jest – I used to be where you are right now – not understanding why Java needed any changes and now I am on the other side and I understand why. There is a very fundamental reason why Java needs to change or die – it is the imminent software crisis that we are almost in in the midst of facing – multi-core programming. I admit it is a long shot, from switch-case statements to multi-core programming – but there is a connection – functional languages.

  10. 10 peter lawrey

    If you can choose the string constants used you can use strings which map to enums which make efficient lookup tables and a readable switch statement.
    This is also a handy way of keeping track of the strings used, with compiler validation and keeping them broadly in sync between sender and receiver. (However hyphen would need to be mapped to something like under score)

  11. 11 antsbull

    What everyone here seems to have missed is that if you need big if..else blocks or switch statements in your code, then your code smells in the first place! That is a sure indicator of a poor design.

    Polymorphic behaviour is the way to go in these situations (if possible). if..else..if..else* smells a lot more than switch statements, and performs like a dog at the same time – its a good indicator that you need to re-design your program.

    On the point about switch statements, where performance is necessary, then they are the way to go – e.g. game or graphic engines, high-perf real time java, element identification when processing massive XML documents using a SAX parser etc.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



Calendar

June 2008
M T W T F S S
« May   Jul »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Follow me

twitter flickr LinkedIn feed

Subscribe by email

Enter your email address:

Archives


Categories

Tag Cloud


Listening