views:

265

answers:

4

I was looking at the null object pattern and i am wondering if it worths implementing it or use "if" checks for nulls in my code intsead. As i looked at the implementations it seems hard to keep objects well synchronized with their null implementations. By making changes to the main object we have to check that the null object behaves as expected and its easy to make implementation errors. Isn't it ?

EDIT

Avoid checking for null: http://www.invisible-city.com/sharon/2009/03/null-object-pattern-when-slacker-is.html or http://journalofasoftwaredev.wordpress.com/2008/08/19/null-object-pattern-by-example/

+3  A: 

If your object being null is going to be a norm throughout your code, you'd might as well use the pattern. I check for null when an object has not been created and it needs to be instantiated. I do not really use null for anything else, and I certainly don't use it to mean no behavior defined.

If however, you are using null to mean the behavior hasn't been defined yet or the default behavior is nothing, then certainly use the pattern.

AlbertoPL
A: 

I make sure my IEnumerable items are empty enumerations instead of null, but if something really is missing, what's wrong with null? Occasionally I need to distinguish between uninitialized and missing in a lazy initialization situation, but then I typically use a separate boolean variable to indicate the state so any value (including null) is valid for the target object itself.

280Z28
+1  A: 

From my experience I don't feel it is hard to keep a Null-Object in sync. If you do have this problem, your object may have too many responsibilities as it is subject to a lot of change.

I tend to use this pattern if I can actually define such an object in terms of letting a default behaviour flow well. E.g. A Null Object for a Query Manipulation is one that leaves the original query untouched. A Null Extension to some other object is one that does nothing.

I find it at times a pretty clean pattern to avoid checking with ifs for optional behaviour that may or may not exist at a certain state of my app.

flq
+1  A: 

I've had great success using null objects with my Factories and IoC implementations. They are especially useful for vertical features of an application. I wouldn't create one for an action that is core to your application.

For example, you have an IPrinter interface and a couple objects that implement it -- PrinterX and NullPrinter. In the IPrinter initialization, you can try to start PrinterX but if it fails, you return a NullPrinter instead. In this case, printing is a feature of the app but not a requirement for it to run successfully.

Austin Salonen