Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad style to use NullPointerException to test for null? [closed]

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?

like image 360
Carsten Avatar asked Jan 24 '11 03:01

Carsten


1 Answers

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.

like image 72
Konstantin Komissarchik Avatar answered Sep 25 '22 23:09

Konstantin Komissarchik