Tuesday, June 06, 2006

NUllObject and Visitor

I have a problem with nulls: they are not objects. I cannot handle a null like any other object: I have to stop, check if it is null or not, and only after that, go on.

The problem is partially solved by throwing (checked) exception: now I have to handle an exception, instead of a null, which might have been propagated, unseen, unheard, through the stack, god-knows-where.

To the rescue comes NullObject: special object, implements the interface, does nothing.
But how do we close the implementation, but still we leave room from improvements: the Visitor: "Visitor lets you define a new operation without changing the classes of the elements on which it operates." (Actually the NullObject should be provided, in my case, by an O/R mapping layer, but I want to extend this object, for my needs). In this case, every "normal" object should do the double dispatching:

accept(Visitor v) { v.visit(this); }

only the NullObject should do nothing:

NullObject.accept(Visitor v) { }

And in C# where we have delegates, the Visitor could be a function/delegate.

-- apparently I am not the first one which thought of NullObject and Visitor.

No comments: