• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NullObject

 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's the intent for the NullObject:

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
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic