[Design Patterns] Null Object Pattern

Design patterns are a chapter that I believe every developer should be familiar with. Design patterns are not to be used in every line of code but you should know as many as you can in order to know when to use them – when they will simplify your code.

The Null Object Pattern is a pattern that I came across recently and found really useful.

Let’s consider the following code :

class DB
{
    public static Person GetAPerson()
    {
        /*
        Implementation not important
        */
    }
}

public abstract class Person 
{
   public abstract bool IsHungry();
   public abstract void Eat();
}

We have an abstract class that represents our object and our database.

Now let’s get our person from our database and feed it!

public void FeedService()
{
    Person person = DB.GetAPerson();
    if (person != null && person.IsHungry())
        person.Eat();
}

I have written the above code hundreds of times and liked it not even one  Sad smile You always have to check for null and having this more than one time make the code less readable. Can we do anything about that?

Yes, we can… with the Null Object pattern that makes the above code prettier and less error-prone.

All we need to do is to implement the interface (our abstract class) one more time but this time we will do it inside our Person class like this :

public abstract class Person
{
    public abstract bool IsHungry();
    public abstract void Eat();
        
    public static readonly Person NULL = new NullPerson();
    private class NullPerson : Person
    {            
        public override bool IsHungry() { return false; }
        public override void Eat() { /* Do nothing */ }
    }
}

Our FeedService now looks like this :

public void FeedService()
{
    Person person = DB.GetAPerson();
    if (person.IsHungry())
        person.Eat();
}

And our Database method like this :

public static IPerson GetAPerson()
{
    if(/* Not Found */)
        return Person.NULL;
    else
        /* The db record */
}

We implemented our NullPerson class as a private nested class and we exposed a single instance of that class so that nobody else could create another instance (what design pattern can we use to achieve that?). Why? Because then we can say (if needed) :

if(obj == Person.NULL)

If we had many instance of that class the above statement wouldn’t be valid.

So by using the above pattern we can ensure that our methods will always return an object and our code will be more readable and less error-prone!

8 Comments

  • Arun Mahendrakar on said

    Reply
    




Arun Mahendrakar

    Clear and simple. Thanks.
    $1
    $1Arun

  • 




Uwe

    I did that once and I'm still not sure whether this has more benefits or drawbacks.
    $1
    $1It feels a little bit like eating exceptions by wrapping code in a
    $1
    $1try { ... } catch ( Exception ) {}
    $1
    $1block.
    $1
    $1Probably you would take longer to find issues in your code, although the checking for NULL has benefits.

  • Juan Nallar on said

    Reply
    




Juan Nallar

    I don't think it is a good idea to treat the object as not null when it actually is null. A null object says there is not an object at all, and the business rules can act according to this. I agree with Uwe's comment. Also, reading the code, I can say that "A null person can be hungry and eat", which sound confusing, at least.

  • 




Paul

    It's a very useful pattern, though like all design patterns you don't apply it willy-nilly. I think John's example is a less commonly used scenario for the NullObject. NullObject, in my experience, is best used for "optional" services. For example, let's say you have a notification API, and no notification providers (e.g. email, sms, etc) have been selected / configured. Rather than have each part of your app check to see if a service has been injected before calling the common methods on the service ,you just have the default notifier provider be a do-nothing NullObject.
    $1
    $1With data access code, like this example, I tend to agree that it's more semantically correct to actually have the null checking in most cases (which doing result == Person.NULL does too, btw...), and requires less overall code, though in the case of enumerables I do tend ot return an empty set rather than a null, so maybe I'm a hypocrit. :D

  • 




djsolid

    Thank you all for your comments! Feedback is ALWAYS more than welcome!
    $1
    $1Maybe the example wasn't the best use of this pattern but I strongly believe that when you explain something you should do it a simple as it gets even if it sounds stupid. The reader should first understand a pattern and then try/decide when use it.
    $1Perhaps a separate post like "When to use Null Object Pattern" could be more appropriate to include all those valid considerations. I think Paul got the point! ;)

  • 




dave

    I'd suggest that the term 'Empty' rather than NULL may be preferable in many cases, as in EventArgs.Empty

  • 




djsolid

    That's correct! Thanks dave!

  • Alicante Airport on said

    Reply
    




Alicante Airport

    I guess you will want to put a facebook button to your site. Just marked down this blog, however I had to make this manually. Just my suggestion.

Add a Comment (gravatar-enabled)