I have some code along the following pattern:
return a().b().c().d().e();
now since every one of those methods could return null
, one would usually test for this:
if( (a()!=null) && (a().b() != null) && ....) {
return a().b().c().d().e();
} else {
return null;
}
(and maybe use some local variables to avoid duplicate calls)
I'm tempted to do:
try {
return a().b().c().d().e();
} catch (NullPointerException e) {
return null;
}
Is that considered bad style? inefficient? Or quite ok?
Don't do this. Throwing and catching exceptions is fairly expensive when compared to basic null checks.
You might also be interested to know that syntax has been proposed for a future version of Java that would make this simpler. It would go something like this:
a()?.b()?.c()?.d()
The "?." operation would be an optional version of the "." operator. If LHS is null, it would return null at that point instead of trying to evaluate RHS. Exactly what you are looking for, but I am afraid it didn't make the cut for Java 7. Don't know the status of this feature for Java 8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With