From: Albert Wagner Date: 2002-09-13T08:09:03+09:00 Subject: Re: not grasping the method overloading/multi-dispatch thing On Thursday 12 September 2002 03:40 pm, Tim.Hunter@sas.com wrote: > In Phil's example, it seems like "meth" is testing the argument's > class, not its type. According to my copy of _Design Patterns_, the > type of an object is the set of methods to which it can respond. If > two objects respond to the same set of methods then they have the same > type, even if they aren't objects of the same class. I haven't read _Design Patterns_, but I like this definition. The set of methods of a class is really a sort of description of behaviour, often several distinct behaviours. > > For me, testing an argument's class is a code smell. What do I care if > "s" is a Foo or a Bar, as long as it responds to the methods I need to > send it? I try to design my classes and methods so that, if I want > method "A" to accept as arguments objects that are created from > different classes, then each of the classes should implement the set > of methods that "A" will send. As far as "A" is concerned, all the > objects have the same type. > > So, for the case where you want to "overload" concat to accept EITHER > String objects or Fixnum objects: > > concat("A", "B") -> "AB" > concat("A", 1) -> "A1" > concat(1, 2) -> "12" > > then you define concat as > > def concat(arg1, arg2) > arg1.to_s + arg2.to_s > end > > Since both String and Fixnum objects respond to to_s, they're both the > same type as far as concat is concerned. That is true. Yet, there is an implied contract where arg1 and arg2 must respond to #to_s. As a mind game, assuming that argument typing were really desirable, and forgetting for a moment the objections, what would be a cool way to specify the _behaviour_ expected from argument objects? (Not using initializing code like #responds_to, etc.) Smalltalkers tended to adopt the convention of prefixing a class name with a- or an- (aString, anInteger); but Smalltalk was single inheritance, without mixins. > > On 12 Sep 2002 17:57:41 GMT, ptkwt@shell1.aracnet.com (Phil Tomson) > wrote: > > (snip) > > >I'm kind of torn between the two sides on this one... > > > >Currently if we need a method that does two different things based on > >the type of an argument we have to do: > > > > def meth(s) > > case s > > when Integer > > #do something > > when Float > > #do something else > > end > > end > > > >It _would_ be nice to be able to declare two meth methods as shown above > >instead of having to test the type of the argument. > > > >However, I also agree with David that this could change the nature of the > >language. I also suspect that there will be a performance > >hit for all code even if you don't use method overloading. IF it could be > >implemented in such as way as to not impact performance if you don't use > >the feature, then I'd probably lean towards doing it. > > > >Phil