You could use null objects instead of null values. Sniff
would then do nothing if any objects in the call chain are null objects.
This would not throw an exception:
person.Head.Nose.Sniff();
Your null classes could look like this (you could also use them as singletons and have interfaces for IPerson
, IHead
and INose
):
class NullPerson : Person {
public override Head Head { get { return new NullHead(); }
}
class NullHead : Head {
public override Nose Nose { get { return new NullNose(); }
}
class NullNose : Nose {
public override void Sniff() { /* no-op */ }
}
As a side note, in Oxygene there's an operator for this:
person:Head:Nose:Sniff;