Multiple Dispatch and Common Lisp Object System (CLOS)

common-lispcommon-lisp-object-systemlispobject-oriented

I have never written software in Common Lisp, but in Scheme and Clojure as well as C++ and Python. Yet I have had a look at the Common Lisp Object System (CLOS) in Common Lisp and Dylan. Now when comparing it to OOP in the Simula tradition, CLOS and lets say C++ and Python class system have polymorphism as a common trait.

They seem to differ in the way how data and methods are organized, in the Simula family, methods are an integral part of classes, sub-items if you will while with CLOS they are defined outside of classes and are rather generalized procedures.

Common Lisp proponents typically argue that virtual methods in Simula-family programming languages are quite limited since they are invoked only according to the first-argument object (this or self). CLOS generic functions are selected for several arguments, thus something like (pseudo code)

method draw(c : Device, d : Drawable) ... 

can be implemented for arbitrary Canvas and Drawable combinations.

method draw(c : Printer, t : Triangle)....
method draw(c : Printer, t : Image)....
method draw(c : Screen, t : Image) ....

In Simula-family languages, this would be more difficult, since draw would have to be associated with either the Device or the Drawable family of objects. The canonical solution seems to be the Visitor Pattern http://en.wikipedia.org/wiki/Visitor_Pattern .

Upon learning CLOS, I was quite amazed that most OO programming languages do not offer multiple dispatch – and – wondered if there are specific reasons, why one might associate methods so closely with one specific class. Are there specific advantages for single dispatch?

  • ambiguity of multiple dispatch: i.e. lets say I have a subclassing A and b subclassing B. The method foo(A,B) implemented as foo(a,B) and foo(A,b), which implementation would a call of foo(a,b) invoke? Is this the only reason?
  • "Modularizing", methods in the class are near.

Is there more to it? Have language designers and creators taken a stance on this matter?

Best Answer

Single dispatch is somewhat easier to implement, and multiple dispatch is rather rarely needed in practice according to research by Muschevici et al.

You can find more information in the Wikipedia article on multiple dispatch; for instance, it also explains why the CLOS method of defining multimethods may be a better fit for Lisp's extremely uniform syntax, rather than for the more prevalent nesting of methods within classes.

Related Topic