Search
Close this search box.

“Provide an object as a surrogate for the lack of an object of a given type. The Null Object provides intelligent do nothing behavior, hiding the details from its collaborators.”

public class Person {
  private string _name;

  public Person(string name) {
    this.Name = name;
  }

  public string Name {
    get { return this._name; }
    set { this._name = value; }
  }

  // Null Object Pattern Implementation
  private static Person _nullInstance = new Person("");
  public static Person NullInstance {
    get { return _nullInstance; }
  }
}

So now we can use the code like this in other classes.

public class Company
{
    private Person _person = Person.NullInstance;
    
    // removed for clarity.
}

You can also do neato things like: (also read Mike Nichols on Null Objects (sort of))

if(Person.NullInstance.Equals(somePerson))
{
    //do stuff
}

Talk about intention revealing! Now you may be saying “Whoa there dru. Whats so bad about a null ref check?”

if(somePerson == null) { //do stuff }

Not much really, if the concept of a NullPerson changes I have already implemented it and I only have to change the one NullInstance if I need some new semantic, compared to every null check if I had used null ref checks. Nulls are a computer software concept not a Domain concept. Clear as mud? Good.

So what if we use an O/RM like NHibernate? Should the framework store the Null object in the database?

What does it mean that “the null object” is in the database?

It means that you are going to take a hit to the database to pull the object out. Although it will be a light record since it has empty values. It means that you are going to have another record in the database that is nothing but blanks. But this just doesn’t really hold much of a candle to the benefits to be gained.

uilding out the Null object for your class will force you to define the null state and its behavior, which I think is a good thing. Nulls in the database have always lead to a heated discussion amongst DBAs. The concept of the blank state as talked about by 37signals jumps out at me. Even though the article talks about UI screens, it also applies to our code, and how we choose to program empty behaviors. Why are we choosing to miss out on this very important programming logic concept? You would think that if an Order had a NullCustomer that it would be an important thing to recognize. Not to mention by using this pattern you can help avoid the nasty NullReferenceException.

Ok, so this was another horribly written pattern post. Hope you could follow along

Null Object at c2

Nulls Suck

Random page with a humerous but good Null Object reference

AOP and Null Object pattern (Artima)

This article is part of the GWB Archives. Original Author: Null Object Pattern

Related Posts