Re: dynamic binding on parameters, how ??



Responding to Bogado...

I want to create a class hierarchy for geometric elements, each
element must know how to report if he intersect with other element.
The interface is the following :

abstract(?) class Element
{
// naive implementation.
public boolean interset(Element e)
}


class SquareElement extends Element
{
// how to intersect with a generic element
public bool intersect(Element &e)

// how to intersect with a square element
public bool intersect(SquareElement &e)
}

class CircleElement extends Element
{
// how to intersect with a generic element
public bool intersect(Element &e)

// how to intersect with a square element
public bool intersect(SquareElement &e)

// how to intersect with a circle element
public bool intersect(CircleElement &e)
};

The problem is that most OO languages I know (java, C++, D) don't do
dynamic binding based on the parameters of a call. Is there a pattern
for this behavior?

Actually, I think they do. You don't need to enumerate the combinations in every subclass. You just need to do it in the Element superclass for each possible target argument. Each subclass then provides its own implementation of the intersect() for each target identified in the superclass' arguments. That implementation will provide the subclass' view of the intersection versus the target type. The language will handle the binding to the subclass implementation method. Essentially this works out to be operator overloading.

The basic problem is that you need a combinatorial number of intersect() methods; one for each combination of owner geometric shape and every possible shape it can intersect with. The closest pattern to that is the GoF Visitor pattern.

However, if you have a lot of geometric shapes, I would look for a different way to abstract the invariants of intersection so that they can be expressed generically in one or a few behavior implementations. Then one can use parametric polymorphism to describe the differences in terms of data (either as common attributes of Element or as a smallish number of specification objects). [The category on Invariants and Parametric Polymorphism on my blog has some examples.]


*************
There is nothing wrong with me that could
not be cured by a capful of Drano.

H. S. Lahman
hsl@xxxxxxxxxxxxxxxxx
Pathfinder Solutions
http://www.pathfindermda.com
blog: http://pathfinderpeople.blogs.com/hslahman
"Model-Based Translation: The Next Step in Agile Development". Email
info@xxxxxxxxxxxxxxxxx for your copy.
Pathfinder is hiring: http://www.pathfindermda.com/about_us/careers_pos3.php.
(888)OOA-PATH



.