Wednesday, August 20, 2008

From the "things I wish Java had" file...

Often you'll find yourself writing code similar to the following:
String childName = root.getChild().getName();
Now, if root.getChild() returns null, you'll get a dreaded NullPointerException. There are a couple ways to guard against this of course, but they're fairly verbose. You could check each traversal point for null...
String childName = null;
Node child = root.getChild();
if (child != null) {
childName = child.getName();
}
That works, but it gets messy quickly if you have another traversal or two (and yes, I know, excessive depth is a bad code smell).

Alternatively, you could do something like this:
String childName = null;
try {
childName = root.getChild().getName();
} catch(NullPointerException ignored) {
}
But you could really end up littering your code with ignored catch blocks.

Ideally, I would love to have a method of saying "traverse as far as you can, but return null if you encounter null along the way". Perhaps a special operator?
String childName = root,getChild(),getName();
Anyway, I'm sure there are languages out there that support this notion. It's high on my list of desired features for an alternative to Java!