From: Matt Armstrong Date: 2002-02-14T03:10:11+09:00 Subject: Re: qualms about respond_to? idiom Paul Brannan writes: > On Thu, Feb 14, 2002 at 01:11:39AM +0900, Dave Thomas wrote: >> start tags would have >> >> def handle_stack(stack) >> stack.push(name) >> end > > Does this really belong in the stream object itself? Should a tag > have to have knowledge of how the data structure it is being put > into operates? What if I wanted to create a binary tree of tags and > other stream elements; should I then have a handle_binary_tree > method in all my stream objects? > > Using your solution seems nice, since it means that the dispatcher > needs less knowledge about the objects it is handling, but it means > that the objects need more knowledge about the dispatcher. Is there > a good way around this tradeoff? Examples of this kind of thing abound in OO languages. Ruby's Hash needs a 'hash' method on the objects it stores. Ruby's Array needs a <=> operator on the object (this also takes care of your binary tree example). This isn't unnecessary coupling -- without these methods, the Hash/Array would have no idea how to handle the objects they contain. You could make a similar argument for handle_stack. But I agree that sometimes this can be taken too far -- handling this particular NXQML problem polymorphically ends up spreading the details of how the stack is processed all over the place. This may very well reduce maintainability more than "branching on interface" by using responds_to?. -- matt