Wednesday, August 08, 2007

Unboxing Gotcha in Java

In a recent blog post, Java wiseman Norman Richards, points out that this innocent-looking line of code contains a gotcha that most IDEs (he checked Eclipse, I checked IntelliJ) don't warn you about:

int sucker = thisMethodReallyReturnsAnIntegerNotAnInt();

Due to autoboxing (well, technically, unboxing), this code could set sucker to null, which pretty much guarantees the dreaded NullPointerException.

What Richards doesn't say is that this code is so innocent looking (and the bug possibility so little recognized), that almost no one would write a unit test for this assignment. At least, that is, until it blows up the first time.

Good catch. OK, back to work: Ctl-F "Integer"...

4 comments:

Anonymous said...

Just to be clear, the example wasn't mine. I was just sarcastically criticizing the original posters point. I do concede that you have to pay a little bit of attention when using primitives now, whereas you didn't before. But this is really not something that should surprise anyone. If I were him, instead of blaming autoboxing, I'd be complaining about whatever logging/error handling deficiency was obscuring the simplest possible null pointer exception

Andrew Binstock said...

Well, I was intrigued. I haven't yet been bitten by this problem and had not previously thought about it. To see how widespread knowledge of this issue is, I checked the major books on Java. None of them mention it. Only McLaughlin and Flanagan's Java 1.5 Tiger Developer Notebook from O'Reilly brings it up.

So, I suspect there are lots of developers unwittingly waiting to trip over this.

Jeffrey Fredrick said...

Well you can probably guess what I did... I took this code:

public class SuckerPunch {

int punch(int x) {
int sucker = thisMethodReallyReturnsAnIntegerNotAnInt(x);
return sucker + x;
}

Integer thisMethodReallyReturnsAnIntegerNotAnInt(int x) {
if (x == 5) return null;
return x;
}

}

and put it into the JUnitFactory web demo and hit generate.

Of course this is really a simple case, but I like your point that this will trip people up, and what are the chances they'll write tests for it?

Andrew Binstock said...

If you run JTF's code through the JUnitFactory demo, it does test for the unboxing problem. It's one of eight unit tests generated for this code snippet. Pretty cool.