I’m refactoring a big class that has a lot of checks for null all over the place into using the null object pattern. So far it’s been an almost smooth change but I am having a couple of issues with the end result and I would like to know if there is a better or different approach or even to go back the way it was.
The biggest problem is that I have the following code:
IMyObject myObject = GetMyObject();
if(myObject != null && !myObject.BooleanProperty)
DoSomething();
So as you can see I could probably remove the null check from this condition but I have a boolean property which if set to the default value will execute a piece of code. If I always return true I might introduce subtle bugs that would be painful to find and eliminate.
Another problem is that I’ve had to modify a check from null like this:
if(myObject.GetType() != typeof(MyNullObject))
return false;
DoSomething();
This is just plain ugly since instead of just checking for null, now I have to check the type. This kind of situation happens three times in the class since I am not returning one of the object’s properties or executing one of its methods I must do this check.
And lastly the object has a couple of DateTime properties which are not nullable and the architect does not want them to be nullable. Again by having the MinDate value as default some nasty bugs could crawl into the code.
So there you have it. Is this a case in which the null object pattern is just worse than the spaghetti null checks scattered all over? Is there a better way to accomplish this?
Thanks for your answers.
The Null Object pattern is about a tradeoff – you gain with the elimination of null checks, but pay with another class to maintain.
I’d suggest adding an
IsNullboolean property to your interface/base class.The normal implementations return
false; your null object returnstrue.This allows you to avoid tests against exact types, and is clearer about your intent. You can also use this as a test in the code that deals with dates, allowing you to retain your non-nullable date properties.