technology

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! :)

Kaneda’s bike?

It was the end of the 80′s and as a dorky teenager, I was fascinated by Katsuhiro Otomo’s Akira, and in particular, its main character‘s bike. This childhood’s dream of a bike seems eerily close today with the EV-X7 prototype electric bike. Looks like I won’t have to wait until 2019 after all! ;)

Treehugger