Not? operator in Java, so as Hari points out, you have to do what the "long wind" is. However, it can be argued that this is good, since it prevents the use of zeros.
For example, in the OP code, why do you set val to null if it or not? Suppose this is a function and val is returned. This is the smell of code: it just pushes the requirement of another zero check for users of your code. It becomes an endless loop of null checks, completely cluttering up code and confusing logic, because programmers often cannot tell if this is legitimate logic, or if a former paranoid programmer quietly ignores errors. Do not imitate PHP! . Quote from this great conversation:
"When you come across something that is doing something meaningless or interrupting with an error, it (PHP) will do something meaningless."
PHP makes a terrible design choice. It is much better to abort an error with an error than to do something meaningless.
Instead, you should ask questions such as:
- What does it mean that a will be null? Is this a programming error? If so, add a RuntimeException / IllegalArgumentException. If this is critical code and you βcannot fail,β at least write that you are processing something suspicious, so it may be fixed.
- What if the a.child.getValue () object itself returns null? How will my caller tell the difference between this zero and "a or child null" null? They can not.
- If there is a good default, use it. If you are using a collection or array, do not pass the value "null" to the value "empty". Skip a
Collections.emptyXXX() , for example. emptyList or empty array. Instead of setting String to null, consider setting it to the empty string "" . By the way, this makes your hashCode(), equals(), and compareTo() lot easier! - Use the Sample Null Object. . If a is an instance of Foo, define a static final Foo.NULL that has a child whose value is something "nullish" - either null or "".
Sometimes you really cannot do any of this. There are good reasons why the arguments are null, or you should allow backward compatibility with a previous poor design or third-party library. IMO, this should be rare, and you should document what is happening. And perhaps you should return something other than zero (or 0) to reflect this. for instance
In the OP example, it looks like there might be some kind of XML node, and the Java XML interfaces are huge and creating a good NULL object for one of them would be a huge deal. (Hmm, maybe a good open source project?). However, in this case, you will most likely call a.child.getValue() lot. Write a little utility to handle this and process zeros. Instead of long null checks everywhere, at least they are encapsulated by several useful methods. DRY. And maybe the fact that the checks are long encourages you to make a better design. So, the flaw ?. The operator was good, right ?:-)