This is a pattern which I’ve started using recently – there’s a good example in “Agile Patterns and Principles…”.
Consider the following class:
And now how we might consume such data:
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:
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:
- Raising an Exception is an expensive operation that should be avoided if possible
- 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: –
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:
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…