Almost two years ago now (#1, #2), I wrote about the idea of being able to modify the way Java handles the situation where a method is called on a null value. Normally this causes an exception; I was wanting such a call to return a null instead, so that the result is more like what happens with XPaths when a node in a path doesn't exist. For example, the XPath
/document/person/address
doesn't cause a program exception if there is no <person> element, whereas
getDocument().getPerson().getAddress()
will throw an exception if "getDocument().getPerson()" returns null. These exceptions make it painful to use Java (etc.) for working with XML, because you end up with so many try/catch blocks to deal with of the places that an exception could possibly be thrown.
So, it was interesting when I stumbled across the fact that Groovy (a Java-based scripting language) solves this issue! Groovy has a "?." operator, which returns null if called on a null, and executes the method normally if called on an object, i.e. "a?.b" is equivalent to "a == null ? null : a.b". So
getDocument()?.getPerson()?.getAddress()
will return null if "getDocument()?.getPerson()" returns null. That makes Groovy (for this and other reasons) a better way to write your XML processing code in Java, if you are trying to keep your code as simple and maintainable as possible.