Null Object For Every Class

In ExtremeFormsForCppCode, MichaelFeathers describes an implementation-hiding technique in CeePlusPlus. An interesting side-effect is that this allows you to define a NULL object for every class and to avoid checking for NULL pointers all over the place. I have added this page in the hope that Michael or others familiar with this technique will elaborate on this. Comments welcome... -- BrianMosher


I actually added that to Michael's page, so it's not his fault. I got the idea from a Smalltalker who says that he does this as a matter of habit. It probably works better in Smalltalk since you can define null objects for literally everyting as opposed to C++ where you might get into trouble when you want your NullObject to return another NullObject but the return type is "int". You could also get into trouble with algorithms that don't terminate when they encounter null behavior or for which there is no "null" behavior. Nonetheless, this is something that I'm looking forward to trying. -- PhilGoodwin

This is explored at great length elsewhere here. There is at least one Smalltalker - yours truly - who believes this to be an incredibly bad idea, because it moves the problem it purports to solve somewhere else and introduces problems of its own. If the intent is to avoid testing for null (or "nil", in Smalltalk), the approach in question introduces many kinds of Nil. This, in turn, leads to unanswered questions about whether these are or are not equal to each other. In practice, you therefore still have to test or compare them - only now you do it somewhere else. This antipattern may be appealing upon first inspection, but it quickly soured in my mouth after experience. -- TomStambaugh

The NullObjectForEveryClass pattern has some merits and flaws that need to be considered separately.

Merits:

Flaws:


Ya gotta love your nulls. I have found it helpful to take the perspective that null is the initial value for everything, in the sense that if you declare something to exist, then it exists, as null, from that point in time until it has a "legitimate" value.


Interesting to note that, in C# 2.0 with the use of NullableTypes and ReferenceTypes? as members within a class or struct, this is the default behaviour.


OctoberZeroSix

CategoryCpp CategoryNull


EditText of this page (last edited September 11, 2013) or FindPage with title or text search