ArticleslgStudy

computer science

Double dispatch

Double dispatch is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Double dispatch rather than just read about it. In short: In software engineering, double dispatch is a special form of multiple dispatch, and a mechanism that dispatches a function call to different concrete functions depending on the runtime types of two objects involved in the call. In most object-oriented systems, the concrete function that is called from a function call in the code depends on the dynamic type of a single object and therefore they are known as single d…

Key takeaways

  • Double dispatch belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Double dispatch to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Double dispatch from memory before moving on to harder problems.

Reference excerpt

In software engineering, double dispatch is a special form of multiple dispatch, and a mechanism that dispatches a function call to different concrete functions depending on the runtime types of two objects involved in the call. In most object-oriented systems, the concrete function that is called from a function call in the code depends on the dynamic type of a single object and therefore they are known as single dispatch calls, or simply virtual function calls. Dan Ingalls first described how to use double dispatching in Smalltalk, calling it multiple polymorphism.

Overview The general problem addressed is how to dispatch a message to different methods depending not only on the receiver but also on the arguments. To that end, systems like CLOS implement multiple dispatch. Double dispatch is another solution that gradually reduces the polymorphism on systems that do not support multiple dispatch.

Use cases Double dispatch is useful in situations where the choice of computation depends on the runtime types of its arguments. For example, a programmer could use double dispatch in the following situations:

Sorting a mixed set of objects: algorithms require that a list of objects be sorted into some canonical order. Deciding if one element comes before another element requires knowledge of both types and possibly some subset of the fields. Adaptive collision algorithms usually require that collisions between different objects be handled in different ways. A typical example is in a game environment where the collision between a spaceship and an asteroid is computed differently from the collision between a spaceship and a spacestation. Painting algorithms that require the intersection points of overlapping sprites to be rendered in a different manner. Personnel management systems may dispatch different types of jobs to different personnel. A schedule algorithm that is given a person object typed as an accountant and a job object typed as engineering rejects the scheduling of that person for that job. Event handling systems that use both the event type and the type of the receptor object in order to call the correct event handling routine. Lock and key systems where there are many types of locks and many types of keys and every type of key opens multiple types of locks. Not only do you need to know the types of the objects involved, but the subset of "information about a particular key that are relevant to seeing if a particular key opens a particular lock" is different between different lock types.

A common idiom The common idiom, as in the examples presented above, is that the selection of the appropriate algorithm is based on the call's argument types at runtime. The call is therefore subject to all the usual additional performance costs that are associated with dynamic resolution of calls, usually more than in a language supporting only single method dispatch. In C++, for example, a dynamic function call is usually resolved by a single offset calculation - which is possible because the compiler knows the location of the function in the object's method table and so can statically calculate the offset. In a language supporting double dispatch, this is slightly more costly, because the compiler must generate code to calculate the method's offset in the method table at runtime, thereby increasing the overall instruction path length (by an amount that is likely to be no more than the total number of calls to the function, which may not be very significant).

Examples

Ruby A common use case is displaying an object on a display port which can be a screen or a printer, or something else entirely that doesn't exist yet. This is a naive implementation of how to deal with those different media.

The same would need to be written for Oval, Triangle and any other object that wants to display itself on a medium, and all would need to be rewritten if a new type of port were to be created. The problem is that more than one degree of polymorphism exist: one for dispatching the display_on method to an object and another for selecting the right code (or method) for displaying. A much cleaner and more maintainable solution is then to do a second dispatch, this time for selecting the right method for displaying the object on the medium:

C++ At first glance, double dispatch appears to be a natural result of function overloading. Function overloading allows the function called to depend on the type of the argument. Function overloading, however, is done at compile time using "name mangling" where the internal name of the function encodes the argument's type. For example, a function foo(int) may internally be called __foo_i and the function foo(double) may be called __foo_d. Thus, there is no name collision, and no virtual table lookup. By contrast, dynamic dispatch is based on the type of the calling object, meaning it uses virtual functions (overriding) instead of function overloading, and does result in a vtable lookup. Consider the following example, written in C++, of collisions in a game:

If you have:

then, because of function overloading,

will print, respectively, Asteroid hit a Spaceship and Asteroid hit an ApolloSpacecraft, without using any dynamic dispatch. Furthermore:

will print ExplodingAsteroid hit a Spaceship and ExplodingAsteroid hit an ApolloSpacecraft respectively, again without dynamic dispatch. With a reference to an Asteroid, dynamic dispatch is used, and this code:

prints ExplodingAsteroid hit a Spaceship and ExplodingAsteroid hit an ApolloSpacecraft, again as expected. However, the following code does not work as desired:

The desired behaviour is to bind these calls to the function that takes apolloSpacecraft as its argument, as that is the instantiated type of the variable, meaning the expected output would be Asteroid hit an ApolloSpacecraft and ExplodingAsteroid hit an ApolloSpacecraft. However, the output is actually Asteroid hit a Spaceship and ExplodingAsteroid hit a Spaceship. The problem is that, while virtual functions are dispatched dynamically in C++, function overloading is done statically. The problem described above can be resolved by simulating double dispatch, for example by using a visitor pattern. Suppose the existing code is extended so that both Spaceship and ApolloSpacecraft are given the function

Then, while the previous example still does not work correctly, reframing the calls so that the spaceship is the agent gives us the desired behaviour:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Double dispatch

Start with the simplest possible case. Write down what Double dispatch claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Double dispatch before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Double dispatch ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Double dispatch

In research
Double dispatch appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Double dispatch in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Double dispatch is common in secondary-school and first-year university syllabi. It links to neighbouring topics Method (computer programming), Software design patterns, so understanding it makes those chapters shorter.
In everyday life
Look for Double dispatch outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Double dispatch” →

How to study Double dispatch in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Double dispatch means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Double dispatch out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Double dispatch in simple terms?

In software engineering, double dispatch is a special form of multiple dispatch, and a mechanism that dispatches a function call to different concrete functions depending on the runtime types of two objects involved in the call. In most object-oriented systems, the concrete function that is called…

Why does Double dispatch matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Double dispatch?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Double dispatch.

Tags

  • Method (computer programming)
  • Software design patterns

Keep exploring