Encapsulate the absence of an object by providing a substitutable alternative that offers suitable default do nothing behavior.
In the situation where I have a JDBC Connection reference which I check for null; and if it's null, I will attempt to create a NEW connection - does that qualify for the use of a NullObject pattern ? Thanks Pho
posted 14 years ago
Only if there are other places in the code where the connection is used, even if it may not have been opened. The typical use of this pattern is when you have code which would like to use the result of an operation, even if it failed. eg: Here's an example using a traditional null, return value
Now here's the same code using the NullObject pattern:
Note that by guaranteeing that "listNames" will always return a valid array, even if it is an empty one, the code which uses it is made much simpler and more readable. I hope that makes sense.