Misplaced null checks

03 Jan 2006

Can you see the problem in this code?

public class Foo {
 void bar() {
  if (b.equals(a.buz()) && a != null) {
   // do something  
  }
 }
}

If a really is null, there'll be a NullPointerException thrown - because the null check comes after the expression that uses a! This kind of beginner's mistake (or sleepy programmer's typo) can creep into a source code base, but PMD will now root it out. Look for this rule and seven others in the PMD 3.5 release... this week, perhaps? We'll see.

And thanks to Fabio Insaccanebbia for another fine rule!

Support PMD, get the book!