From: Philipp Meier Date: 2002-09-13T19:18:39+09:00 Subject: Re: not grasping the method overloading/multi-dispatch thing --1ccMZA6j1vT5UqiK Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Sep 13, 2002 at 02:22:25PM +0900, Patrick May wrote: > Dale Martenson wrote in message news:<20C86D26= 20F6D411A199009005DC0102016D1830@exchange serve.multitech.prv>... > > 2. It allows for "cleaner" solutions where overloading is the "best" op= tion. > > It could be argued that overloading is needed to satisfy POLS. If Ruby = is > > truly the best OO language, how can it not have overloading!! :-) >=20 > Overloaded methods are the same as a conditional on type. To me, this > is never the best option, not when you can put methods on the class to > convert it to the form you need. >=20 > I'd be curious to see code that >=20 > a. calls for overloading on type > b. couldn't be handled by pushing code up to the classes of the > argument objects Because of Rubys dynamic nature this is IMHO always possible. But is it good design? You will agree, that, as an example, code that formats a business object for reporting certainly does not belong into the business object class but in a reporting class. A solution I proposed before is extracting this kind of methods into a seperate classes which go along the classes you propose the methods belong into. The polymorphic dispatching logic then dispatch by type (untested): class PolyTest @@receivers =3D { :to_html =3D> { String =3D> StringAdapter, Integer =3D> IntegerToHTML }, :to_rtf =3D> { String =3D> StringAdapter, Integer =3D> IntegerToRTF } } def dispatch(method, index, *args) r =3D @@receivers[method][args[index].type] r.send(method, self, *args) end def to_html(doc, object) dispatch(:to_html, 1, doc, object) end def to_rtf(doc, object) dispatch(:to_rtf, 1, doc, object) end def test to_html("", "Test") # =3D> calls StringAdapter.to_html("", "Test") to_rtf ("", "Test") # =3D> calls StringAdapter.to_rtf("", "Test") to_html("", 1) # =3D> calls IntegerToHTML.to_html("", 1) to_rtf ("", 1) # =3D> calls IntegerToRTF.to_rtf("", 1) end end class StringAdapter def to_html(doc, string) doc << "String: #{string}
" end def to_rtf(doc, string) ... end end class IntegerToHTML def to_html(doc, i) doc << "Integer: #{i}
" end end class IntegerToRTF def to_rtf(doc, i) ... end end -billy. --=20 Meisterbohne S=F6flinger Stra=DFe 100 Tel: +49-731-399 499-0 eL=F6sungen 89077 Ulm Fax: +49-731-399 499-9 --1ccMZA6j1vT5UqiK Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) iD8DBQE9gbuefBriNoqItSYRAjFiAJ4nm4UE+N/MoV85ppUjbJXpNd7RiwCgkCuH 0/4HdvTSorQeNftuBzHVtkw= =NAo2 -----END PGP SIGNATURE----- --1ccMZA6j1vT5UqiK--