This is not a tag line!
Java 5 pitfall
Java 5 has some nice improvements over Java 1.4 that really make writing code simpler… Then again sometimes simpler also means dangerous. Case in point, Java 5 auto-boxing. Consider the following method:
public Boolean isValid()
{
// if we don't have any data, we cannot decide so we return null,
// which is why we're using Boolean instead of boolean
if(data == null)
{
return null;
}
else
{
// data.isValid() returns a Boolean
return data.isValid();
}
}
As you can see, we are using Boolean as a return type to provide a ternary result instead of a simple true/false decision: sometimes, we just don’t have enough information to decide and we want to know that. So far so good!
Now, we’d like to use this method within a test:
...
if(isValid())
{
//do something...
}
This code compiles with Java 5 thanks to the auto-boxing mechanism. It would be an error with Java 1.4, however, the compiler in Java 5 transparently converts the Boolean return value to a boolean. Everything seems great: we have a method that provides more information and the code is as easy to read as it was with a method that simply returned a binary result. Except that now, this last piece of code can actually fail and cause a NullPointerException because the compiler converts the code to something similar to:
Boolean tmp = isValid();
if(tmp.booleanValue())
{
// do something...
}
thus causing the NullPointerException if tmp is null… Tricky!
Now, this is nothing new (though I only realized it when I was about done with this post), it’s been pointed out several times already… However, I stumbled on it just now and though I figured out pretty quickly, it was still somewhat surprising. On the other hand, the advantage of only starting to use a Java version so late after it’s been released is that all the potential pitfalls are fairly well documented by now!
Related posts:
- Beware of File.createTempFile By default, File.createTempFile (in Java, of course) creates a temporary...
Related posts brought to you by Yet Another Related Posts Plugin.
| Print article | This entry was posted by Chris on November 14, 2007 at 00:23, and is filed under java. Follow any responses to this post through RSS 2.0. Both comments and pings are currently closed. |
Comments are closed.
