2009-01-09

Dispatch, Static versus Dynamic, Single versus Double or Multiple

I read Stuart Holloway's Java.Next #3 Dispatch and decided to make clear to myself the concept of Dispatch and how it is used.

Dispatch means to call a method of an object and is normally applicable in the context of object-oriented programming. The rest of this summary assumes that there is more than one function with the same name and revolves around selecting the function (or method) to call (see Multiple Dispatch).

Static Dispatch that the system can pick the function to call at compile-time, as opposed to Dynamic Dispatch where the system has to choose the function to call at run-time. Dynamic dispatch can be supported by the programming language (e.g. polymorphism) or implemented in a program (e.g. case-statement).

Single Dispatch means that the system picks the function to call based on one parameter. In common object-oriented languages (e.g. C++, Java or C#), that parameter is the type of the object (see Dynamic Dispatch). For example:

class A { fn(); }
class B { fn(); }

A a;
B b;

a.fn();

When the system encounters a.fn(), the system calls the function fn() in class A because the object a is of the type A.

Multiple Dispatch (or Multimethods) means that more than one parameter is considered when calling a function. Multiple Dispatch gives mentions some languages the support this feature but I'm only familiar with Groovy, so I found this example by Danno Ferrin where the function chosen depends on the types of the object and function argument.

Double Dispatch is a special case of multiple dispatch (see Double Dispatch) where two parameters are considered and it is often implemented using the Visitor Pattern in single dispatch languages.

References

1 comment:

  1. Thanks by the clarification, in the Stuart Holloway's article seems like Groovy doesnt support multiple dispatch, but is nice to know that it indeed does!

    ReplyDelete