NULL Object pattern


This is a pattern which I’ve started using recently – there’s a good example in “Agile Patterns and Principles…”.

Consider the following class:

public class Employee
{
    public static Employee GetEmployeeFromDb (int employeeId)
    {
        Employee Output = null;

        // Do some code here to retrieve the employee - if none is found, leave Output as null

        return Output;
    }

    public int Id { get; private set; }
    public string Name { get; private set; }
    public string Department { get; private set; }
}

 

And now how we might consume such data:

var MyEmployeeObject = Employee.GetEmployeeFromDb (123);

// Check first if an employee was returned
if (MyEmployeeObject != null)
{
    System.Console.WriteLine ("Result from call to get details of employee {0}:", MyEmployeeObject.Id);
    System.Console.WriteLine ("Name: {0}", MyEmployeeObject.Name);
    System.Console.WriteLine ("Department: {0}", MyEmployeeObject.Department);
}
else
    System.Console.WriteLine ("No employee details found.");

 

A slight digression, but one thing I have started doing lately having read Code Complete 2 is to change the way I write the code above to above the (ugly-ish) brace around the null check – if you have lots of inner IF statements you code ends up reading halfway across the page. So I now tend to do it like this:

var MyEmployeeObject = Employee.GetEmployeeFromDb (123);

// Check first if an employee was returned
if (MyEmployeeObject == null)
{
    System.Console.WriteLine ("No employee details found.");
    return;
}

System.Console.WriteLine ("Result from call to get details of employee {0}:", MyEmployeeObject.Id);
System.Console.WriteLine ("Name: {0}", MyEmployeeObject.Name);
System.Console.WriteLine ("Department: {0}", MyEmployeeObject.Department);

 

So now the “default” code path is the “correct” code path i.e. a valid employee was returned, as opposed to the first version where you have the negative of the if statement (i.e. != null) being the regular path. I know some people like to only have a single return statement in a method but I think in circumstances like this it’s obvious what the intent is.

Anyway, even with this, you still have to do the check for null after the call to the DB. Imagine having to do this all over your code, loads of times etc. You code loses focus from the original intent of the method i.e. get employee details and print them out on-screen. An alterative might be a try/catch block. So don’t do a null check, but as soon as the first line is executed we’ll jump to the catch block and print the “no employee details found” message over there. Or maybe our GetEmployeeFromDb method raises an Exception if no employee is found. However, there are two issues with this approach:

  1. Raising an Exception is an expensive operation that should be avoided if possible
  2. More importantly, your “front end” consuming code still has to know that the GetEmployeeFromDb method may return null and code around it. In fact, Try/Catch is probably no more elegant that the if/then above.

Enter the Null Object pattern. Here’s how we can use that pattern to solve this issue:

First the Employee class: –

public class Employee
{
    private static Employee NullEmployee = new Employee { Department = "Not set.", Name = "No employee found", Id = -1 };

    public static Employee GetEmployeeFromDb (int employeeId)
    {
        Employee Output = null;

        // Do some code here to retrieve the employee - if none is found, leave Output as null

        // If no employee was found, return the default "null" employee
        if (Output == null)
            Output = NullEmployee;

        return Output;
    }

    public int Id { get; private set; }
    public string Name { get; private set; }
    public string Department { get; private set; }
}
 

Notice the check we now do to see if Output == null, we return a “default” Employee which has null data, but will never generate a null reference exception. Our client code can now be greatly simplified as we can now guarantee that the GetEmployeeFromDb method will always return an Employee object:

var MyEmployeeObject = Employee.GetEmployeeFromDb (123);

System.Console.WriteLine ("Result from call to get details of employee {0}:", MyEmployeeObject.Id);
System.Console.WriteLine ("Name: {0}", MyEmployeeObject.Name);
System.Console.WriteLine ("Department: {0}", MyEmployeeObject.Department);

There’s no if/ then statement, nothing getting in the way of simply retrieving an employee from the DB and printing the details to the screen. If we were using this employee object in twenty places within the system, all of those areas of code would be simplified by the removal of null object checks.

I’ll blog about slightly more advanced ways of using NULL Object next time…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s