Friday, May 13, 2011

The Null Object Design Pattern

I came across an interesting design pattern recently. Say you have a service that fetches a foo object and calls foo.bar() if some condition is met. Under normal circumstances, you'd have to check if the foo object is null. What if, instead, you could have an object that represents a null foo, and just has no-effect methods. That way, the “null” object could be treated the same way as a normal object. To do this, just write a private inner class that extends foo, have its methods do nothing and return false on condition methods. The outer class will have a static final instance of this, and any outside methods that are supposed to fetch a foo then return this “null” object if they fail.

I found it here

No comments:

Post a Comment