Over a million developers have joined DZone.

When to check for null?

DZone's Guide to

When to check for null?

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}