I’m wondering if it is an accepted practice or not to avoid multiple calls on the same line with respect to possible NPEs, and if so in what circumstances. For example:
anObj.doThatWith(myObj.getThis());
vs
Object o = myObj.getThis();
anObj.doThatWith(o);
The latter is more verbose, but if there is an NPE, you immediately know what is null. However, it also requires creating a name for the variable and more import statements.
So my questions around this are:
- Is this problem something worth
designing around? Is it better to go
for the first or second possibility? - Is the creation of a variable name something that would have an effect performance-wise?
- Is there a proposal to change the exception
message to be able to determine what
object isnullin future versions of
Java ?
If you are sure that
getThis()cannot return anullvalue, the first variant is ok. You can use contract annotations in your code to check such conditions. For instance Parasoft JTest uses an annotation like@post $result != nulland flags all methods without the annotation that use the return value without checking.If the method can return
nullyour code should always use the second variant, and check the return value. Only you can decide what to do if the return value isnull, it might be ok, or you might want to log an error: