Thursday, August 09, 2007

The Good, The Snide, and The Ugly (More on Autoboxing)

Wow. You know you've hit the big time when famed Java geek author Norman Richards gets all snarky on your sh*t. I would like to point out, though, that I never said autoboxing was "evil". I just said it was !cool. And no amount of Richards' sarcastic aping of my (deliberately) satirical-yet-lighthearted take on it is going to convince me otherwise.

The problem, of course, lies in the fact that, pre-autoboxing, there was no question of an assignment to a variable of type int throwing an NPE. For the first 87% of Java's numerical-version-life you just couldn't do it. The concept had no meaning, like the questions "what is north of the North Pole?", or "what color is up?". Or "can I borrow your copy of 'XDoclet in Action'?" (Author's note: because no one in my office has one).

Pre-autoboxing, Eclipse would have flat out disallowed the assignment of an Integer to an int. And here's the important point: Eclipse would have disallowed it, because the compiler would have disallowed it. Because you couldn't assign an object reference to a primitive type, inadvertently or advertently. It wouldn't be a legal assignment, so it wouldn't compile, so there would be no way for it to throw an NPE in production. That's what static typing is supposed to ensure.

In true famed Java geek author style, though, Richards totally misses the pedagogical point when he uses as his sarcastixample the potential NPE-ness of code that deals with String. Which is an object type. Which has since the beginning of Java time been subject to NPE's. As opposed to primitive types. Like int. Which have not. Until autoboxing rocked our world and broke static typing.

I've actually been waiting for someone to snark on my (deliberately) satirical-yet-lighthearted insinuation that I rely too much on my IDE. That was the first point I took away from this whole exercise, and believe me I will be more wary in the future. I'm pretty sure I'm not the first to be burned by such an over-reliance. But in this case, even if I were using Emacs and the command line, I would still have fallen victim to this problem. The fault lies in the language, not in my reliance on any tool.

Bottom line: I don't think it should be too hard to excuse someone who, when seeing an NPE in his stack trace, doesn't leap immediately at the assignment to the int variable.

But maybe that's just me.