Say “No” to “Null”

May 1st, 2010

I was recently asked to write a fairly simple piece of code.  In this simple piece of code, I didn’t handle a null input.  I was asked about what kinds of things I would consider about the input, and I pretty much knew what the asker was going after.

What do you do if “null” is passed in?

My answer may turn out to be a bit of a surprise.

Nothing, I don’t handle nulls in code that I control the use of.

“What?  What?” you say.  “You don’t handle null?  What kind of heresy is that?”  It is the kind of heresy that helps produce elegant code and I will show you why.

How well do you handle null right now?

Would you say that in most of the code you write you properly check all arguments for null?

Or, do you like most developers, handle null in certain cases when you happen to think about it, or after the application dumps a “null pointer exception” stack trace?

Be honest, look at your code if you have to.

The problem is “d00d ur d0ing it r0ng!”

john-mccarthy-programming-completely-wrong

Unless you are some kind of anal retentive perfectionist, you are probably not handling null in every single method call.  That means there are huge potential bugs in the code that you are writing which will throw null pointer exceptions.  That is bad, I agree.

So, if you are not handling it correctly right now, then what can you do to fix that?

Avoiding null in the code you “own”

You can’t control external libraries.  And you can’t control how people will use your code, but you can control the code you write and you can, to a degree, control the code your shop writes.

The better strategy is to never pass null in the first place.

You can either focus your efforts on:

  • Checking for null
  • Not ever passing null
    The more elegant solution is to focus on never passing null.  By doing this you will end up writing less code and avoid decisions about how to handle null inside of a method that doesn’t have enough context to decide what to do.

Let’s look at an example:

public string TransmographyThreeStrings(string first, string second, string third)
{
     if(string.isNull(first) || string.isNull(second) || string.isNull(third))
    {
           // hmm, I donno, what should I do?  Should I throw an exception?
           // should I return an empty string?
           // what if the first string wasn't null, can we still do something meaningful?
           // how will the caller of the method know what I will do?
    }

}

You can see there that we are checking each parameter for null.  The problem is we don’t know what we should do.  We have lots of options, but none of them are obvious.

How much better is it to make sure that we never pass null into methods, rather than write this kind of code in every method?

What about accidentally passing in null?

Many of you are probably thinking at this point that the main way null gets passed into a method is because someone calls a method without knowing that it contains a null value.

TransmographyThreeStrings("Hello", "World", mysteryObject.Text);

Perhaps mysteryObject.Text is null.  You wouldn’t even know it.

Ah, but you can.  Or you can prevent it at least.  Somewhere mysteryObject gets created.  When it gets created its values either get initialized or not.  You can prevent any of its values from being null, several ways:

  • Always initialize variables when they are declared.
  • Use a builder pattern to ensure that objects are always fully constructed before being created.
  • Use properties to provide default values or lazy initialize.
  • Make your objects immutable as much as possible.

The practices that prevent null from accidentally being passed in make your code much more elegant than repeating if blah == null code all over the place.

In general, you should always strive to eliminate the passing of null rather than checking for null.  By doing so you reduce extra lines of code in each method, and are forced to use better design practices.

Exceptions

Yes, there are times when you need to check for null.  If you are writing a library that external developers will use, then you will probably want to check for null in all of your methods that are exposed as part of the API.  (On your internal methods, you don’t need to since you have already cleansed the input.)

Also, if your code is being used as a callback to some API and you don’t know if it can ever pass null into your code, you probably should check for null.

A bad excuse is that other developers may pass null to your method. It is much better as a software shop to put the onus of not passing null on the caller of any method rather than putting it on the writer of the method being called.

You will also reduce your exception handling code, because you will have less exceptions for invalid parameters.

As always, you can subscribe to this RSS feed to follow my posts on elegant code.  Feel free to check out my main personal blog at http://simpleprogrammer.com, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter here.

  • http://buckaroocoder.wordpress.com/ Chuck

    John –

    Timely article as I had just read Robert Martin say the same thing in his book “Clean Code” (which all developers should read).

    Both you and Bob did not say “No Null” (like the popular “No SQL”). I think that, through the comments, it has been clarified that we are talking about the objects created in code. Since a database is external, you probably should do some null checks (especially if you pass datasets around).

    Of course, like anything, this will work only as well as your testing goes, especially the end-to-end testings. If Bob didn’t follow the standards and passed in an uninitialized and that code makes it to production…the response will most likely be a null object check and Bob will probably never hear about it (unless of course, we decide to enforce the programming standards).

    Enjoyed the article and will bring it up to my group today.

    Chuck

  • Schmuli

    There is a difference between passing an invalid null argument to a method and receiving a null return value from a method you called. Null arguments are checked in preconditions (like Code Contracts), and should therefore be checked and dealt with as early as possible. Null return values may be legitimate and generally need to be handled on a per case basis (although you still have empty lists and exceptions where relevant).
    My question is: if I have an internal method which is called by a lot of different public-facing methods that don’t care about the value (they are just passing it on), should the null-check still be in each public method, or can I put a single check in the internal method?

  • http://simpleprogrammer.com John Sonmez

    @Chuck
    @Schmuli

    Thanks Chuck, I appreciate the feedback. I think you get my point exactly.

    Schmuli,

    To answer you question, in my opinion the check belongs in the public facing methods. Now, there is a difference between public methods and public facing methods. If you have a class that you are using internally with public methods, I would lean towards practicing the reduction of use of nulls and checking there. But if you truly have an external API beyond your control, you need to not only check the input for nulls, but treat the input as malicious, and do whatever protection is needed. The place to do it is at the point of entrance.

  • http://www.the-robot-lives.com Keith Brings

    Interesting.

    I’m not sure if I agree but I can see the merit in your argument. Do you also use SAL annotation to help verify that you code is not capable of passing null into your methods?

  • Anonymous

    Sir Charles Antony Richard Hoare, inventor of the null reference

    http://qconlondon.com/london-2009/presentation/Null+References:+The+Billion+Dollar+Mistake