From: Ross Bamford Date: 2005-12-23T01:52:49+09:00 Subject: Re: String > Integer Conversion Problem On Thu, 22 Dec 2005 14:53:54 -0000, wrote: > Hi -- > > On Thu, 22 Dec 2005, Ross Bamford wrote: > >> On Thu, 22 Dec 2005 14:07:03 -0000, jwesley >> wrote: >> >>> Ruby provides enough mechanisms for "controlling the flow" that using >>> exceptions for "normal" conditions is definitely poor style, if not >>> worse. >>> >> >> Okay, good. That was my feeling too. > > I agree in general, although... there's one case where I can't resist, > at least sometimes, and that's this: > > if obj.respond_to("meth") > obj.meth > else > > end > > I really dislike the repetition there, and it also technically isn't > thread-safe: > > a = Object.new > def a.x; end > > Thread.new do > sleep 1 > class << a; undef_method("x"); end > end > > if a.respond_to?("x") > sleep 2 > a.x > end > > => undefined method `x' for # (NoMethodError) > > I don't know any way around it, though, except: > > begin > obj.meth > rescue NoMethodError > > end > > or some variant thereof. (Obviously in true duck-typing cases you > just send the message without this kind of check, but there are cases > where the check makes sense.) > Good point. Now you mention that, I think I'd probably end up going for the latter style in that case anyway, despite my comments earlier about exceptions. I guess it's about a balance between being prepared for exceptions and pre-empting them. Mostly in Java (the only language I've really used exceptions with) the choice is made, since you have to deal with (so-called 'checked') exceptions whenever they might be thrown, so I'm still finding my balance there. I expect that version also makes refactoring easier later on if you decide to move the further up the chain. > I've toyed with the idea of some kind of special "nack" object that > would be returned on these kinds of method calls, but I don't think it > plays well with method_missing. > As a general way for objects to nack method calls? If so, maybe the default method_missing (or equivalent?) could do that, or you can provide your own method_missing to do whatever...? The implications of the metaprogramming stuff on thread safety is a subject that, frankly, worries me. When I understand a bit more I'm looking forward to investigating that side of things. Cheers, -- Ross Bamford - rosco@roscopeco.remove.co.uk