I've been writing software since about 1993, spanning several different domains and programming languages. Always on the look for better and more fun ways to program. I spent much of my youth fencing, and recently I returned to the sport as a coach. Borislav is a DZone MVB and is not an employee of DZone and has posted 15 posts at DZone. You can read more from them at their website. View Full User Profile

When to check for null?

  • submit to reddit

Recently, I started collaborating with a co-worker that likes to very meticulously enforce all pre-conditions in a method. The motivation is clear and noble: (1) detect errors as soon as possible which helps with bug tracking, and (2) be explicit about your expectation which makes code more readable. But as with everything, taken to extreme this can be rather counter-productive both at coding time as well as later. We are coding in Java and by "taken to extreme", here I mean explicitly checking for null values, array boundaries or instanceof everywhere. This sort of discipline is a remnant from languages, in particular C, where dereferencing a null pointer will crash the program. But in a language like Java where the runtime system already does that for you, what's the point? Unless you can do something to avoid throwing an exception if the pre-conditions is not satisfied, why not let the JVM throw the exception, especially since it's going to do that check anyway whether you've done it before or not? For example, in code like this:


public int addProductToDB(Product x)
    if (x == null)
        throw new NullPointerException("Can't add a null product to the database");
    insertProductRow(x.getName(), x.getQuantity());

there's no reason to have that if statement. You will get an NPE with a full stack trace, and line number (in case you were obsessed with code size and turned debug info off, which would mean you've tested enough already), so the only thing you've achieved here is code bloat. Of course there are cases where a null check helps. Here's a variant of the artificial example above:

String makeInsertProductStmt(Product x)
    if (x == null) return null;

public int addProductToDB(Product x)
    String sqlStmt = makeInsertProductStmt(x);
    ... some other code...

Now, clearly the null value would show up later during execution, and probably through a not very informative exception coming from the db driver. So here it would make sense to check for null. It would help detect a bug more easily. Otherwise, keep the code smaller and let the runtime do its job.

Published at DZone with permission of Borislav Iordanov, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)