I recall reading a best practice somewhere that you should neither give nor expect null as the result of a method invocation. This was absolutely the norm in C++ despite the somewhat common notion of the NullObject pattern (http://www.eli.sdsu.edu/courses/spring98/cs635/notes/strategy/strategy.html#slide8); the practice is still so common in .NET languages that I doubt many people are familiar with the notion of a null object.
Today I began self-reviewing my code for a mobile project I am in the process of wrapping up. I found that this notion had made its way into some of my code and for the sake of consistancy I went about repairing my error. The fact that I had things like
CustomerDataAccess dao = new CustomerDataAccess();
CustomerTruck ct = dao.FindByBarcode(bc);
if (null != ct) {
//Do something
}
in (shamefully) about half my code made me take a step back and question the value of what I was doing. First of all, I find it amusing that I still keep to the old C++ "Put your constants on the left hand hand side of any comparison" practice. For those of you who never had the honor of programming C++ the following code would compile, but give you unexpected results:
if (lValue == 3){
// do something
}
//Versus:
if (lValue = 3) {
//whoops...
}
...since both "=" and "==" are valid inside an if statement. To make a long story short, any successful action such as this will return a non-zero value and failure a zero value. In C++ "if (0) " is valid syntax and therfore this could result in a hard to track down issue. My question to my mentors was always "Well, if I can remember to use the const expression as the Lvalue why can't I just remember to do it right?"; but that's neither here nor there.
There are some examples of a NullObject pattern in the current .NET framework, for example using string.Empty instead of "" or null.
Thinking further, many have accidently (mis)used this pattern for value-types in the current .NET language. Have you ever used DateTime.MinValue in your code to signify "No value here" ? In .NET 2.0 we will have nullable value types (http://msdn2.microsoft.com/en-us/library/b3h38hb0) to make this a little bit cleaner for us.
As I replaced code such as if (null != ct) with if( ct != CustomerTruck.None) it certainly did look cleaner and made me feel better about myself as a person but I wondered if it was worth going back over working code to do. One additional benefit is that if I DO forget to check for null (or proper NullObject) in code somewhere, I will likely get some expected behavior rather than a NullReferenceException.
My questions to the community are these: do you have your own argument for using a NullObject Pattern? Do you use the NullObject pattern?
(Thanks to Terski for being my pre-post sounding board yet again)