From: David Alan Black Date: 2002-02-14T01:26:03+09:00 Subject: Re: qualms about respond_to? idiom Hi -- On Thu, 14 Feb 2002, Dave Thomas wrote: > David Alan Black writes: > > > All tags respond to tagStart? and tagEnd? But not all events in my > > stream are tags. So.... > > > > if e.respond_to? :tagStart? > > context.push(e.name) if e.tagStart? > > end > > > > is my way of testing, first, whether it's a tag (but without actually > > checking whether it's a tag), and, second, whether it's a start tag. > > A polymorphic way of doing this is to move responsibility down to the > stream elements. Say each had a method handle_stack. Then your main > code could simply call handle_stack on _all_ tags: > > e.handle_stack(context) > > > start tags would have > > def handle_stack(stack) > stack.push(name) > end > > > end tags might have (I'm guessing - I don't know what your app does > here) > > def handle_stack(stack) > top = stack.pop > raise "Havoc!" unless top == name > end > > > and all other tags would have a null handle_stack > > def handle_stack(stack) > end OK -- but does this suggestion mean that you would see the "responds_to?" idiom as a sign that something's wrong with the code? Actually, this all started for me with my work on NQXML::Dispatcher, when I was originally branching on type: if e.is_a? NQXML::Tag if e.startTag? ... and got enlightened on IRC about not branching on type or depending on type in Ruby :-) So I've learned to think of branching-on-type as a sign that something needs to be fixed; now I'm wondering whether the responds_to? idiom should be viewed similarly (rather than as an acceptable rewrite of branching on type). David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav