When I code I am frustrated with null checks. Especially while coding data structures!
I have to do it as
String val;
if(a != null && a.child != null)
val = a.child.getValue();
else
val = null;
Something sort of this...
Is there a operator like ?. (which is a part of C#) for Java to shorten the burden ?
ะก# example:
String val = a?.child?.getValue();
There is no ?. operator in Java, so, as Hari notes, you have to do things the "long winded" way. However, one could argue that this is a good thing, as it discourages the use of nulls.
For example, in OP's code, why are you setting val to
null
if a or it's child is not there? Let's assume that this is a function and val gets returned. This is a code smell: it just pushes the requirement for yet another null check to users of your code. It becomes an endless cycle of null checks, completely cluttering the code and confusing the logic, because maintenance programmers often can't tell if this is legitimate logic, or a paranoid former programmer is quietly ignoring errors. Don't mimic PHP!. Quoting from that excellent rant:"When faced with either doing something nonsensical or aborting with an error, it (PHP) will do something nonsensical."
PHP makes a horrible design choice. It is far better to abort with an error than do something nonsensical.
Instead, you should be asking questions like:
Collections.emptyXXX()
, e.g. an emptyList, or an empty array. Instead of setting a String to null, consider setting it to the empty string""
. BTW, this makes yourhashCode(), equals(), and compareTo()
much simpler!Sometimes you really can't do any of these things. There are valid reasons for arguments to be null, or you must allow for backwards compatibility with a previous bad design or 3rd party library. IMO, this should be rare, and you should document what happens. And maybe you should return something other than null (or 0) to reflect this. For example
In OP's example, it looks like a may be some sort of XML node, and the Java XML interfaces are huge and creating a good NULL object for one of them would be a huge undertaking. (Hmm, maybe a good little open source project?). However, in that case, you will likely be calling
a.child.getValue()
a lot. Write a little utility function to handle this and handle the nulls. Instead of long winded null checks everywhere, at least they are encapsulated in a few utility methods. DRY. And, arguably the fact that the checks are long winded, encouraged you to do a better design. So the lack of the ?. operator was a good thing, right? :-)