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;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).
Node child = root.getChild();
if (child != null) {
childName = child.getName();
}
Alternatively, you could do something like this:
String childName = null;But you could really end up littering your code with ignored catch blocks.
try {
childName = root.getChild().getName();
} catch(NullPointerException ignored) {
}
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!