Null Object Pattern

Posted by flori Wed, 03 May 2006 08:15:00 GMT

This is a useful pattern to stop worrying about nil checks and the like or to unit test with partially mocked objects:

NULL = Class.new do
  def method_missing(*)
    NULL
  end
end.new

NULL now responds to each unknown method call by returning itself.

In my case this yielded some nice syntax to disable error logging instead of writing to a log file in a DSL:

def null
  NULL
end
# ...
error_to null # in DSL

It worked instantly as intended. ;)

Tags ,  | no comments