Multiple dispatch [was Re: Discussion: ...]

Edward Jason Riedy ejr at lotus.CS.Berkeley.EDU
Mon Jul 24 23:36:56 EDT 2000


And Eric Lorenzo writes:
 - 
 - So yeah, you're reducing encapsulation a bit with multi-methods, [...]

People keep saying that, but I've yet to be convinced.  Even Scott
Meyers isn't too sure.  The idea behind the following article isn't
too far from the CLOS or Dylan view of encapsulation:
  http://www.cuj.com/archive/1802/feature.html

However, note that real impact is only felt when combined with
some way of directing the language system to perform type checks
for you.  If you can stay purely dynamic, multiple dispatch seems
much less important to me.  A function in a module already doesn't
care what type its arguments are...  If you're simply using basic
attribute methods in its arguments, it's already generic enough.

But when you _need_ the types...  And sometimes you do.  Consider
Matlab's non-treatment of the difference between 1x1 matrices and
scalars.  Or the fact that people commonly expect to add a scalar
to a matrix or vector, but not a vector to a matrix.

 - but in my view, that's okay, because arbitrarily encapsulating the 
 - addition of two objects into the class of whichever happens to be on 
 - the left isn't really appropriate, anyways.

Yup.  However, you can imagine encapsulation within the _module_.
That's a CLOS way to think about OO.  Objects aren't necessarily
the unit of encapsulation.

 - Now, to my eye, the latter is far more elegant and matches what's
 - happening conceptually much more closely, since it treats the type of
 - each of the two arguments as if they are of equal importance and uses
 - the same mechanism to deal with both.

You can carry this to an extreme.  See Cecil's predicate objects at the
following super-long URL:
  http://www.cs.washington.edu/research/projects/cecil/www/www/www/Release/doc-cecil-lang/cecil-spec-23.html
Interesting, but unproven.

 - Because C++ takes into account the type of all parameters [...]

At compile time.  The standard implementation is much different 
than that of run-time dispatching (virtual).  Python's entirely 
run-time dispatched.  That makes efficient implementations much 
more difficult.

Oh, and the compile-time flexibility in C++ also seems to help my 
object constructors.  The tradititional dynamic way to make objects
includes passing dictionaries of options, lots of keyed arguments,
etc.  That tends to add a ton of conditionals into my constructors,
and I don't like code with tons of conditionals.  I'm still not sure
if this is a deficiency on my side or not...  Probably is.

Jason, who likes the artificial compile-time / run-time dichotomy 
less and less...



More information about the Python-list mailing list