Women in Technology

Hear us Roar



Article:
  Advanced OOP: Multimethods
Subject:   Not sure where one would use this?
Date:   2003-06-17 23:24:30
From:   anonymous2
Hi,


As a person who has built object-oriented
systems in C++, Python, and perl I'm a
bit confused by the examples chosen.
Eg. I almost never have to switch on the
type of something, except perhaps as a
safety check on a method's argument.


Perhaps the next article could be
about changing an existing class
which has a deep inheritance hierarchy
to use Dispatch. Eg. SimpleHTTPServer.


Thanks.

Full Threads Oldest First

Showing messages 1 through 3 of 3.

  • Not sure where one would use this?
    2003-09-22 12:45:19  anonymous2 [View]

    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.
  • Not sure where one would use this?
    2003-06-18 10:12:00  quilty [View]

    The anonymous poster who wrote:
    |has built object-oriented ...I almost never have
    |to switch on the type of something, except perhaps
    |as a safety check on a method's argument.

    Seems to have missed the point of the article, and probably of OOP. I can barely imagine how you could write ANY OOP program that did not switch on the type of something--that's almost the entire point of OOP.

    Now, of course, switching on type is not done mostly by 'switch' or 'if' or 'case' statements in OOP. It's mostly done on the *type of the object*. If you have a parent class, Super, that implements a .foo() method, and a child class, Sub, that specializes .foo(), then every time you call "instance.foo()" you are switching on the type of -instance-. And if you create a subclass in the first place, it is almost always so that the subclass can work in (some of) the same contexts as the parent (by implicitly switching on type).