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!


David Dossot said...

Check Groovy safe navigation idiom, you will love it.

I tend to use Groovy scripts now for this kind of unsafe operations: since Java6 it is now so easy to access scripting from a standard Java application.

Carl Schmidt said...

That's exactly what I want, thanks! I've gotten so behind on things, am definitely looking forward to catching up...

Anonymous said...

Old blog, I know, but you could always write a wrapper for that behavior. It's not optimal either, but it would be the least cutterful way of doing it.

I just wish there was a destructor in Java. There's a lot of things destructors can do other than releasing memory :(

Freya West said...

The word 'Idioms', in this context, should be taken to mean something like 'Common Practice'. This page isn't an appropriate place to put patterns, it's a place to put example of common solutions to java coding problems. If the Idiom linked to off this page has no code, then its a pattern. If its about using a related group of classes to solve a design problem, then it is a pattern too.

for IT the said...

I have read your blog its very attractive and impressive. I like it your blog.

Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai