Tuesday, November 21, 2006

Null: The Runtime Error Generator

I never for the life of me want to hear another argument about how static typing catches errors at compile. I really don't. It drives me crazy! When you have to cast arguments to get them to the right thing in generic situations, it's frustrating. But, that's not the biggest sin. After writing the following line for the uptenth time:
if (something != null) {
something.doWhatYouWereBornToDo()
}

You know what I mean. It's inevitable in legacy java applications. Now, I generally only do null checks on my inputs and avoid null conditions at all cost. But, the other day it got me thinking:

Null gets around all static type checking at compile time.

It's not a real type. It can be ANYTHING. At compile time, it slips under the radar because it only exists at runtime. So, what is my typing system doing for me? I find NullPointerExceptions tend do great damage on lazy (bad, whatever you want to call it) code. And let's face it, we've all had those days where we weren't exactly on the ball. NullPointerExceptions are sitting there to wake us up.

I really don't mind static typing. But, let's not kid ourselves. Allowing nulls throws out the safety of the compiler catching our dumb mistakes because most of mine are of the null variety (the dumb ones that is).

Of course, we could just reference everything by their interface and do the Null Object pattern and be smart about messages to ignore and which ones to worry about. But, it's a lot of typing without much gain.

Now, you might be saying to me, "But, Blaine, you imbecile! Don't you have nulls in Smalltalk, Ruby, and Lisp?" Yes, we do and it's called nil. But, we don't pretend to catch all of our dumb mistakes up front. And our nil is an ordinary object which we can add messages to. Nil, our null, is a little bit more powerful. Does it still sting when we make a programming mistake? You bet it does.

Enough on that, just don't get me started on primitive arrays in java. They are even sneakier and there's a plethora of stuff that the compiler doesn't catch.

Till next rant, keep your objects small and your messages plenty. AMEN!

No comments: