From: Tim Hunter Date: 2002-09-14T08:03:12+09:00 Subject: Re: not grasping the method overloading/multi-dispatch thing Other folks have already answered the general version of this question much more authoritatively and eloquently than I can.Somewhere later on in this thread, Patrick May says "Conditionals on type are a smell of code that could be moved from the users of a class to the class itself." I agree, and you've already hinted at part of a solution: add a method to Signal that does the proc{function.to_s}.call. Add a similarly named method to Proc (or a subclass of Proc and then require the argument to be an object of the subclass). That doesn't help for Fixnum or nil arguments, though. Here I gotta tell ya, this makes me think it's time for some refactoring. Since "function" can be any of 4 wildly different things, I wonder if assign_at is doing the work of more than one method. Just thinking out loud, you understand. Lastly, I admit I'm not smart enough to have thought of Phillip's approach. But you know, that hash looks like it's sending methods based on an object's type, and Ruby will do that for us anyway if we ask it. On Fri, 13 Sep 2002 13:43:05 -0400, Philipp Meier wrote: > On Fri, Sep 13, 2002 at 04:42:52PM +0900, Phil Tomson wrote: > >> Yes, but what about an example like this (This is some actual code I >> have which I hesitate to show because I'm sure it's pretty smelly code, >> but I'm also not sure how else to do this): >> >> class Signal >> #.... >> def assign_at (relTime=0,function=nil) >> #schedule an event >> nextValue = case function >> when nil >> Proc.new.call >> when Proc >> function.call >> when Signal >> proc{function.to_s}.call >> else #should probably be Fixnum >> function >> end >> @eventQueue[relTime] = nextValue >> nextValInQueue = @eventQueue.shift >> @next_value = nextValInQueue if nextValInQueue >> end >> >> def assign(function=nil) >> if function >> assign_at(0,function) >> else >> assign_at(0,Proc.new) >> end >> end >> >> #.... >> end > > What about the following? > > class Signal > > @function_handlers = { nil => NilHandler.new, > Proc => ProcHandler.new, > Signal => SignalHandler.new, > Object => DefaultHandler.new > } > > def assign_at(rel_Time=0, function=nil) > nextValue = @function_handlers[function.type].invoke(function) ... > end > end > > class SignalHandler(function) > proc{function.to_s}.call > end > > class DefaultHandler(function) > function > end > > ... > > -billy. >