Code reuse is very important for developers, most of the patterns and refactorings exist soley to reduce the smell of duplicated code. Null checks are one of the biggest culprits of duplicated code. It is also, to a degree, a concern that often gets scattered through out an application and isn’t properly separated. Without testing and/or good documentation, it’s often hard to determine the expectations of a method that returns a reference type or a nullable value type. Often, unnecessary, paranoid, null checks are incorporated to deal with the problem.
The null object pattern almost solely exists as a pattern to reduce code, so if it cannot reduce the amount of code you are writing, don’t use it!
The idea is that instead of setting a refernece type to null initially, you set it to an implementation of the type that executes “null behavior” if methods are called on it’s contract that would normally throw a null reference exception.
- Redcue code
- Separated concerns when handling null logic
- Not familiar to newer developers
- Can complicate code, make sure it is actually reducing the amount of code before implementing! This is not a pattern to start with in a standard toolset!
Say we have a contract for a type:
public interface IThing
and your system made a large number of calls to this Do method but had to check if the Thing was null before calling Do/Execute, you could replace the initial value of a reference to it with a Null implementation instead, then if someone calls a method on a null instance it won’t have any side effects (including null reference exceptions) if it wasn’t initialized already.
public class NullThing : IThing
public void Do()
public bool Execute()
Then, anywhere that used this type could initilize to the NullThing:
public class ThingHaver
private IThing _Thing = new NullThing();
public IThing Thing
_Thing = value;
What would be really cool is if we could somehow overload the default operator in c# and set what it returns. Then, if we used an abstract base class of IThing (ThingBase), we could implement this to return our NullThing(), assuming that behind the scenes the compiler relied on wiring up calls to default whenever it ran across:
private ThingBase _Thing;
Then we wouldn’t even have to set our variable to NullThing! Though maybe I’m getting too far off on a tangent here :) My one concern with this pattern is that it is very easy to produce a disparity in a team if they all aren’t aware of the pattern or it’s implementation in a particular scenario.