Why does Fowler PoEAA p. 498 define the null-object pattern in the following way (sample shortened, language is c# but doesn't matter):
public class Customer
{
public virtual string Name {get; set;}
}
public class NullCustomer : Customer, INull
{
public override Name
{
get { return "ImTheNull";}
// setter ommitted
}
}
INull
is used as a marker interface.
I don't really like this approach for three reasons:
- Properties need to be marked virtual
- I can't seal my entity classes anymore
- At least (n+1) new types are introduced (n null objects, one marker interface)
Why isn't it implemented like this:
public class Customer
{
public static readonly Customer NullCustomer = new Customer(){Name = "ImtTheNullCustomer";}
public string Name {get; set;}
}
I have generally found all of Fowlers examples well thought and there clearly must be something I have missed here.
The reason for the inheritance is to override the behavior of the class. The way you are thinking about it seems to me like you are going to check if the object you have is equal to the
NullCustomer
static instance to make a decision, however the point of the null object is to uphold the Liskov's substitution principle.In other words, you use the null object to set a reference and you will not have a special check for it, you will just use it and it should have a different behavior (really a lack of behavior).