Archive for August, 2011

Zeebruges

Monday, August 29th, 2011

Some pictures from our mini-trip to Zeebruges:


New in Java 7 (02) – Switching over Strings, beyond good & evil

Tuesday, August 9th, 2011

In the first post of this series, I’ve told you a bit about the new diamond notation which is a nice addition and provides for better code readability and less verbosity. And not only that, but since we’re typists first and programmers second, it also allows us to increase the LOC / minute count (and whether that is a good thing is actually open to debate) ;-) (sorry for those poor hunt and peck typists among you).

For this second post, I want to talk about a feature that has been requested about 16 YEARS ago and that was finally implemented in Java 7: the ability to write switch statements with String cases. I won’t insult you with an example, if you want one, then check the official docs.. Also, I won’t cover the performance aspects, which other people have already explained quite nicely.

As many of you know, it’s a feature that has been available for a long time in many other programming languages (e.g., C#, JavaScript, ruby, …) and even though hardcoding String literals should be avoided whenever possible, there are still cases where it makes sense.

To cater for the lack of that feature, multiple workarounds were used. One of which (the ugliest IMHO) being to use if-then-else blocks to handle all the cases for non-binary decisions (more complex than simple if-else), which indeed leads to unreadable/unmaintainable code (even though it is context based and sometimes if-then-else blocks make more sense than using a switch).

Another approach, which I think is way better on multiple levels is to define an enum with a fromString(String) method and use the enum values in a switch via the valueOf method. That technique allows to avoid repeating hardcoded Strings all over the place and keeps the code easily refactorable. Not only that, but it is also way more flexible. For example, in the fromString method (or whatever you decide to call it), you can decide whether you want to support case sensitivity or not, how to treat null values, etc. You can find a nice writeup of that idiom there.

The support for String objects in switch statements is very welcome, but keep in mind that it isn’t the silver bullet and that it shouldn’t be used in all cases (haha) :)