ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
Article:
  Advanced OOP: Multimethods
Subject:   Not sure where one would use this?
Date:   2003-09-22 12:45:19
From:   anonymous2
Response to: Not sure where one would use this?

The benefit of multiple dispatch is to gain successively more precise about the types of the arguments. If you are given two objects that are "shapes" (foo and bar), you invariably use single dispatch to do things like foo.center(). You can use double-dispatch to tell the *other* object precisely what you are:


shape.intersect(Shape bar)
{
bar.dd_intersect(*this);
}


The call to bar.intersect will not go to shape.intersect, but to the overloaded function closest to the true type of bar - might be shape, might be circle, rectangle, etc. Better, that call will also know the detailed type of the first object, hence
circle.dd_intersect(Circle foo)
circle.dde_intersect(Square foo)
...


You end up with, to quote from a very old text game, a maze of twisty functions, all alike - except where there are special cases.


The general case is implemented in Shape; the special cases are handled where they are needed.


The best part, for my needs when I've used this, is that you can have the fall-back situation be an error in the base class.