Wednesday, April 6, 2011

Switch String in, break remains

Java 5 saw a flurry of very useful language enhancements in Sep 2004: generics, autoboxing, annotations, the enhanced for-loop, among others. The Java 6 release in Dec 2006 brought no language enhancement to make the developer's life easier. Java 7, however, to be released in mid 2011, comes with a few.

Changes to JSR 334 under Project Coin include a try-with-resources statement, catching multiple exception types in the same catch block, binary literals, underscores as a digit group separator in numbers, and the most useful, strings in switch statements.

This sounds as a relief, though I wonder what took them 15 long years to figure out the use of a switch statement that accepts a String object in the expression. I believe in real-world programming, we use more if-then-else in Strings than in ints, at least I get to do that in many cases in projects I've worked upon.

While they were at it, I'd have expected them to do away with the break at the end of every case in a switch-case block. It is a nuisance in many cases, because you generally have one flow for one case. Of course there might be cases, as in the example in the link given above, where you might need the fallthrough. A cleaner solution would have been to use some other keyword, maybe continue, whenever a fallthrough is desired, and break as the default implementation, the way Perl and Google's Go do it.

No comments:

Post a Comment