When to check for null

I often get truly tired of all the null checking when programming. I keep asking myself, is this really necessary? For example, I am the one coding it, and I am the only one who will be sending stuff into those methods. This is of course not always the case, but very often it is.

Anyways, I found some good advice on when we should check for null values and thought I could note it down here and share it.

One thing to remember is that the code you write today, while it may be a small team and you can have good documentation, will turn into legacy code that someone else will have to maintain. I use the following rules:

  • If I’m writing a public API that will be exposed to others, then I will do null checks on all reference parameters.
  • If I’m writing an internal component to my application, I write null checks when I need to do something special when a null exists, or when I want to make it very clear. Otherwise I don’t mind getting the null reference exception since that is also fairly clear what is going on.
  • When working with return data from other peoples frameworks, I only check for null when it is possible and valid to have a null returned. If their contract says it doesn’t return nulls, I won’t do the check.

Very good advice :)

About Torleif

Was born in Hønefoss (Norway) the 20th of January 1985 around 16:05. I am a Seventh-Day Adventist, a software developer and a hobby juggler.
This entry was posted in Software Development and tagged . Bookmark the permalink.

2 Responses to When to check for null

  1. Vegar says:

    Have you seen the ‘Null object pattern’ ? Haven’t tried it out my self, but it would reduce amount of null-checking.

    And then there is the colon-operator’ in Delphi Prism.

    • Torleif says:

      Seen it and tried to use it a bit. For example when I make things that returns iterators or arrays I try to always return empty ones instead of null.

      The colon-operator in Delphi Prism looks quite nice! In C# you have the ??-operator which is not as smooth, but still helps a bit with null checks.

      Instead of doing:

      var something = possibly_null != null ? possibly_null : alternative_if_null;

      You can shorten it to:

      var something = possibly_null ?? alternative_if_null;

      So if you had an object to represent a null or empty object you could do like this:

      var something = (some_container ?? Container.Empty).SomeProperty;

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>