From: Philipp Meier Date: 2002-09-13T18:52:13+09:00 Subject: Re: not grasping the method overloading/multi-dispatch thing --n8g4imXOkfNTN/H1 Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Sep 13, 2002 at 08:41:33AM +0900, Patrick May wrote: > Philipp Meier wrote in message news:<200209121311= 50.GA25625@o-matic.net>... > Is this a good example of the types of dispatches you often do? >=20 > Dispatching on type smells like there is a need for some polymorphic > method. For example: >=20 > def description( build_target ) > case build_target.class > when Compile > "compile libraries" > when InstallDependencies > "install dependencies" > else >=20 >=20 > "unknown target" > end > end >=20 > (I doubt that code in the wild would be this obvious) >=20 > To me, the point of OO programming is to have one conditional that > picks the type. If you find conditionals on type downstream from your > factories, then I think it's a sign of methods that should be on the > classes, i.e. Compile.description, InstallDependencies.description, > etc. This generally true. I had the need for this kind of polymorphism when I wrote some kind of generic Object to XML filter for the WebWork framework. The general idea was to plug in adapter classes which have the know how of converting a certain class to a meaningful xml document. The pseudo-code of the adapter looked like this class Adapter def adapt(node, object, attr_name) adapter =3D adapters.find(object.type) adapter.adapt(document, object, attr_name) end end class ObjectAdapter def adapter(adapter, node, object, attr_name) new_node =3D object.appendChild(attr_name) object.attributes.each do |a| adapter.adapt(new_node, object.send a, a) end end end class StringAdapter def adapter(adapter, node, value, attr_name) new_node =3D object.appendChild(attr_name) new_node.appendText(value) end end class ArrayAdapter def adaptObject(adapter, node, array, attr_name) new_node =3D node.appandChild(attr_name) array.each do |e|=20 adapter.adaptObject(child_node, e, "item"); end end end Here, i implemented the polymorphism in the method Adapter#find which tries to find an Adapter that matches a specific type as possible. -billy. --=20 Meisterbohne S=F6flinger Stra=DFe 100 Tel: +49-731-399 499-0 eL=F6sungen 89077 Ulm Fax: +49-731-399 499-9 --n8g4imXOkfNTN/H1 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) iD8DBQE9gbVqfBriNoqItSYRAtF2AJ0c7BOKp/EBx3narm8HjDY9MOcsTwCfbrnj baEeiOZ9gQWzrzN0NkQGlkM= =x/eY -----END PGP SIGNATURE----- --n8g4imXOkfNTN/H1--