On Mon, 2002-11-25 at 20:24, Hal E. Fulton wrote:
> Well... one way would be
> 
>   class NilClass
>     def method
>       default_value
>     end
>   end
> 
> But many will frown on this, and it
> only works for *one* case anyway...

This is fine for small scripts ... I've done it myself.  But I would
avoid it in reusable libraries where I don't have control over name
conflicts in common system classes.

There is an alternative that is only a little more work and is more
scalable.  It is called the Null Object Pattern.

First you create you own "Null" class.  Define any methods you want to
have default behaviour for.  E.g.

  require 'singleton'
  class MyNullObject
    include Singleton
    def method
      default_value
    end
    # More methods here as needed.
  end

Then, just arrange your properties to be initialized to your special
"null" object.

  class MyObject
    attr_reader :property
    def initialize
      @property = MyNullObject.instance
    end
  end

Now, you never have to check to see if "property" is null or not.  It
will always have some behavior (if only the default one).  For example,
its usage is:

  mo = MyObject.new
  mo.property.method   # no need for checking!


-- 
-- Jim Weirich     jweirich / one.net    http://w3.one.net/~jweirich
---------------------------------------------------------------------
"Beware of bugs in the above code; I have only proved it correct, 
not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)