what to do for nulls

A logical follow up to null checking in the extreme and Never return Null Arrays, is what we should be doing when a null does get returned.

The problem

Consider the following method:

public void method() {
StringBuilder builder = UnreliableCode.createBuilder();
if ( builder != null ) {
builder.append("data");
}

This time, a null check is appropriate because we can’t guarantee createBuilder() works as advertised.  Let’s assume that the method is either designed to return null on error or is just plain buggy.  Let’s also assume it is not owned by us so we can’t change it.

That leaves us with the question of what we should do if builder returns null. The code currently fails silently. Yuck! This means if createBuilder returns null, we just don’t append the data. Finding this bug relies on hunting it down based on the side effects. Letting Java throw the NullPointerException (or throwing our own more logical exception) based on it is preferable to failing silently. Or in this case, it might make sense to recover by creating a new StringBuilder ourselves.

Another example of handling nulls poorly is:

public void method() {
StringBuilder builder = UnreliableCode.createBuilder();
if ( builder == null ) {
System.out.println("builder is null");
} else {
builder.append("data");
}

Ok so we logged it.  Does that mean we don’t care and can proceed?

I once got into a debate with a former coworker about what should happen when a variable is unexpectedly null. The essence of his argument was that “code shouldn’t throw null pointers.” While this is true in some respects, it isn’t always the case. If you have a null pointer error condition, why should the code do something else to mask it?

What I think we should do

Contrary to the above, I don’t advocate throwing null pointers on purpose.  In this case, where I think it is likely to happen, I would want to handle it explicitly.  However, seeing code littered with null checks because “you never know when something might return null” seems worse to me then letting the NullPointer get thrown.  Especially if there is nothing logical to do in handling it.  When a null pointer really is unexpected is when I think it should be treated as such rather than masked.

Regardless, I think the user shouldn’t see the NullPointer or ArrayIndexOutOfBounds or any other unexpected RuntimeException.  This winds up being a matter of writing a top level handler.  For an applet/swing type app, it winds up being a matter of intercepting them to show a user message.  For a web app, it can be redirection to a custom error page.  For a command line app, it can be a text error message.  The key being that the user doesn’t care that there was a NullPointer.  He/she cares that “something went wrong.”

Leave a Reply

Your email address will not be published. Required fields are marked *