What's the first thing that pops into your head when you see Java + You = Powerful... or Java = Innovation...? Coming right out of the Java Puzzler session, my first thoughts were: Is this an assignment or a comparison? Does it have a side effect? And will the data types clash? This is the mind set that Joshua Bloch and Neal Gafter put you in when they tell you about the pitfalls of the Java language.

To give you a picture how they work: One of the code samples they showed contained an inconspicuous call to Boolean.getBoolean("true") to parse user input. But this method is not what it seems: getBoolean() tells you a system property named by the argument exists and is true! If you expected it to convert the string to a boolean, you want to use Boolean.parseBoolean(). The take-away message for developers? Read the Javadoc! And for API designers? Use the priciple of least astonishment when naming your APIs, please.

In another example, they extended a collection class, but the outcome wasn't as expected. Java inheritance is one of the key language features, and you can trust it--But make certain to never extend a class that was not explicitly designed for extension. Assume you had extended a collection class's addAll() and add() methods to have a side effect: increasing a counter. Now, what if addAll() was internally implemented to rely on add()? Then the counter is increased twice for every call of addAll(), which is not what you intended. The point is, you can't always know how certain methods are implemented. If you must override these classes, Bloch and Gafter suggest a reusable forwarding class wrapper.

Yet another seemingly obvious, but tricky code sample included a custom comparator. The goal was to find "the (number) one" in a list of Integers. The code looked fine, but many failed to spot the implicit autoboxing: The items to be compared were Integer objects, not ints. A custom comparator that uses == for objects is broken, because this operator compares the identity of objects, and not their numerical values. What did you learn? When employing the == and != operators, make certain Java's autoboxing doesn't hand you objects instead of primitives.

The take-away message for every developer out there: If you're not sure what it does, it doesn't do what you think it does! The Puzzler session teaches even the most seasoned Java developers something shockingly new about the language that they believe to know inside out. So don't pass up tools such as Findbugs or a good IDE that offers quick fixes, editor hints, and javadoc integration--it will save you time and nerves, and prevent the most common mistakes.

Curious to learn more? Crack code snippets, read sample chapters, and order the book from javapuzzlers.com. You can also buy your copy directly at the JavaOne store.

Comments:

Post a Comment:
Comments are closed for this entry.

This blog copyright 2009 by GD