On Mon, 9 Jul 2001, Keith Hodges wrote:

> Has anyone implemented the Null pattern in ruby yet?
>
> I am giving it a go, but its the kind of thing that has lots of subtle
> implications.

I have implemented a "Null_Mutex", but I have not implemented a generic
class for the "Null pattern".  If I understand correctly, though, this
would be pretty useful.

The big problem with this is that you really need to know what interface
to implement, and what the semantics are.  For example, with the
Null_Mutex, I need a synchronize method that does not lock a mutex, but
still calls the passed block:

class Null_Mutex
    def sychronize(*args)
        yield *args
    end
end

On the other hand, it's not possible to simply check for whether a block
is given, because a Null_List probably shouldn't call the block:

class Null_List
    def each
    end
end

Another possibility is to have a generic Null_Object class that, when
created, reads another class's methods and creates a default
implementation for each method.  The implementation would do nothing
except call a block if one is given (like the synchronize method above)
and return the last value in the block if one was, or return self
otherwise.  A Null_List could then be easily created by deriving from
Null_Object and then implementing any methods that need to have different
semantics from the default implementation.

Most methods are likely to have a different implementation, though
(consider that the return value is probably different between methods;
some may return 0, others nil, and others self, and some might even raise
an exception), so there really isn't much to gain from doing this (apart
from perhaps gaining an is_null_object method, but you'd also have to add
such a method to Object).

It might be best to just re-implement the Null Pattern for each type.

Paul