Null checks

Java code - and not only it - tends to be littered with null reference checks like:

void foo(SomeClass obj) {
    if(obj != null) {
        obj.doSomething();
    }
}

While there are many legitimate cases for such code, quite often this code is a bad idea.

The essential question to ask with such code is: is a null value for the variable (parameter) a known possiblity with well-defined semantic, or is the if statement there just to prevent a NullPointerException (or similar for other languages).

If it is the first case, fine. Just make sure the code handles correctly whatever the meaning of a null pointer/reference is.

In the other case, it means that the pointer/reference is never supposed to be null, and it is a bug somewhere if the pointer/reference is null. In such a case, the if statement does several wrong things:

  • it clutters the code, making it less readable;
  • it makes less clear what the intention of the code is, and what are the preconditions for the function or the code assumptions in general;
  • if that pointer really comes in null, it hides (postpones) the error instead of (noisily) throw a NullPointerException.

    What to do instead? Well: