oopcommon-lispclosdynamic-dispatch

Is generic dispatch in Common Lisp Object System the same as Dynamic Dispatch in classic OOP?


I am reading the book Object Oriented Programming in Common Lisp from Sonja Keene.

In chapter 2, the author says:

The procedure for determining which methods to call and then calling them is called generic dispatch. It happens automatically whenever a generic function is called.

This reminds me of the Dynamic Dispatch definition which is (according to Wikipedia):

Dynamic dispatch is the process of selecting which implementation of a polymorphic operation to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented programming languages and systems.

Unfortunately, the wikipedia does not have an entry about generic dispatch.

Thus, I would like ask:

1 - Are dynamic dispatch and generic dispatch basically the same thing? What are the similarities?

2 - And what are the differences? Is dynamic dispatch some sort of subset of generic dispatch due to the flexibility of CLOS?


Solution

  • Generally generic dispatch just means selecting an implementation of a generic function based on one or more of its arguments.

    This applies to single dispatch (like Lisp's Flavors system) or multiple dispatch (like Lisp's CLOS).

    In both CLOS and Flavors a generic function bundles various methods. These methods may be different method types (primary, before, after, ...) and/or specialized for one or more argument types.

    The generic dispatch of Flavors and CLOS chooses the applicable methods and computes an effective method, this one then gets called with the provided arguments.

    Example:

    CL-USER 7 > (defmethod greet :before ((w world)) (princ "hello"))  
    #<STANDARD-METHOD GREET (:BEFORE) (WORLD) 40200211B3>
    
    CL-USER 8 > (defmethod greet ((w world)) (princ "world") (values)) 
    #<STANDARD-METHOD GREET NIL (WORLD) 40200221F3>
    
    CL-USER 9 > (defmethod greet :after ((w world)) (princ "."))  
    #<STANDARD-METHOD GREET (:AFTER) (WORLD) 402002317B>
    
    CL-USER 10 > (greet (make-instance 'world))
    helloworld.
    

    As you can see, the generic dispatch mechanism automatically calls multiple different applicable methods in a specified order.

    The generic dispatch of CLOS can also select methods based on all required arguments and their types -> multiple dispatch.

    Summary: generic dispatch in CLOS (and Flavors, ...) means selecting applicable methods AND combining them to an effective method. This is a specific form of dynamic dispatch. Dynamic dispatch OTOH is often just calling one method and often only selected based on one argument. CLOS then supports generic dispatch in the form of multiple dispatch and method combinations.