Patternadvanced
Double dispatch
Also called double dispatching, multiple polymorphism.
Double dispatch selects a method by the run-time types of two objects. In a single-dispatch language, the first call dispatches on the receiver, and it calls back the argument, which dispatches again.
- Family
- behavioral-design
- Intent
- Dispatch a call to different concrete functions depending on the run-time types of two objects, in a language whose calls dispatch on the receiver only.
- Also called
- multiple polymorphism
Intent
Double dispatch is a special form of multiple dispatch. It dispatches a function call to different concrete functions, depending on the run-time types of two objects that are involved in the call.1
Problem
In most object-oriented systems, the function that a call runs depends on the dynamic type of a single object, the receiver. These calls are single dispatch calls, or virtual function calls.1 Sometimes the correct computation depends on the types of two objects. In a game, the collision between a spaceship and an asteroid is computed differently from the collision between a spaceship and a space station.1 Other use cases are the sorting of a mixed set of objects, event handling that depends on the event type and the receiver type, and lock and key systems.1
Function overloading looks like a solution, but in C++ overloading is resolved at compile time. A call through a reference to Spaceship selects the overload for Spaceship, even when the object is an ApolloSpacecraft.1 Python's functools.singledispatch has the same limit at run time. The dispatch happens on the type of the first argument only:2
This code runs but gives a wrong answer on purpose.
from functools import singledispatch
class Ship: pass
class Asteroid: pass
@singledispatch
def collide(a, b):
return "unknown"
@collide.register
def _(a: Ship, b):
return "ship takes damage" # the type of b is not known here
@collide.register
def _(a: Asteroid, b):
return "asteroid hits something" # the type of b is not known here
print(collide(Asteroid(), Ship()))
print(collide(Asteroid(), Asteroid())) # meant: asteroids break apart
asteroid hits something
asteroid hits something
Solution
Systems such as CLOS have multiple dispatch. In other systems, double dispatch is a way to get the same result with two single dispatches.1 The first call dispatches on the receiver. The receiver then calls a method of the argument and passes itself. The name of that second method tells the type of the first object, and the second call dispatches on the type of the argument.
a.collide(b) first dispatch: on the type of a
|
+--> b.collide_with_asteroid(a) if a is an Asteroid
+--> b.collide_with_ship(a) if a is a Ship
|
+--> second dispatch: on the type of b
In the C++ example of Wikipedia, each spaceship class gets a virtual function collideWith(Asteroid& asteroid) that calls asteroid.collideWith(*this). The type of *this is static in each class, so overloading now selects the correct function.1
Example
The example files show one program in each language. Ship and Asteroid each have collide, which calls back the other object with a method named for its own type. The program collides four pairs and prints:
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
class Ship:
name = "ship"
def collide(self, other):
return other.collide_with_ship(self) # second dispatch, on other
def collide_with_ship(self, ship):
return "ships bounce"
def collide_with_asteroid(self, asteroid):
return "ship takes damage"
class Asteroid:
name = "asteroid"
def collide(self, other):
return other.collide_with_asteroid(self)
def collide_with_ship(self, ship):
return "ship takes damage"
def collide_with_asteroid(self, asteroid):
return "asteroids break apart"
pairs = [(Ship(), Asteroid()), (Asteroid(), Ship()), (Asteroid(), Asteroid()), (Ship(), Ship())]
for a, b in pairs:
print(f"{a.name} + {b.name}: {a.collide(b)}")
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
- Verdict: idiom. Python dispatches a method call on the receiver only, so
collidecalls back the other object.functools.singledispatchdispatches on the first argument only, so it does not give double dispatch.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
struct Ship;
struct Asteroid;
struct Body {
virtual ~Body() = default;
virtual std::string name() const = 0;
virtual std::string collide(const Body& other) const = 0;
virtual std::string collideWith(const Ship& ship) const = 0;
virtual std::string collideWith(const Asteroid& asteroid) const = 0;
};
struct Ship : Body {
std::string name() const override { return "ship"; }
// *this has the static type Ship here, so the Ship overload is chosen
std::string collide(const Body& other) const override { return other.collideWith(*this); }
std::string collideWith(const Ship&) const override { return "ships bounce"; }
std::string collideWith(const Asteroid&) const override { return "ship takes damage"; }
};
struct Asteroid : Body {
std::string name() const override { return "asteroid"; }
std::string collide(const Body& other) const override { return other.collideWith(*this); }
std::string collideWith(const Ship&) const override { return "ship takes damage"; }
std::string collideWith(const Asteroid&) const override { return "asteroids break apart"; }
};
int main() {
std::vector<std::pair<std::unique_ptr<Body>, std::unique_ptr<Body>>> pairs;
pairs.emplace_back(std::make_unique<Ship>(), std::make_unique<Asteroid>());
pairs.emplace_back(std::make_unique<Asteroid>(), std::make_unique<Ship>());
pairs.emplace_back(std::make_unique<Asteroid>(), std::make_unique<Asteroid>());
pairs.emplace_back(std::make_unique<Ship>(), std::make_unique<Ship>());
for (const auto& [a, b] : pairs) {
std::cout << a->name() << " + " << b->name() << ": " << a->collide(*b) << "\n";
}
}
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
- Verdict: idiom. The callbacks are overloads of
collideWith. Inside each class the static type of*thisis that class, so overload resolution picks the correct callback, and the virtual call picks the class of the argument.
interface Body {
String name();
String collide(Body other);
String collideWithShip(Ship ship);
String collideWithAsteroid(Asteroid asteroid);
}
class Ship implements Body {
public String name() { return "ship"; }
public String collide(Body other) { return other.collideWithShip(this); }
public String collideWithShip(Ship ship) { return "ships bounce"; }
public String collideWithAsteroid(Asteroid asteroid) { return "ship takes damage"; }
}
class Asteroid implements Body {
public String name() { return "asteroid"; }
public String collide(Body other) { return other.collideWithAsteroid(this); }
public String collideWithShip(Ship ship) { return "ship takes damage"; }
public String collideWithAsteroid(Asteroid asteroid) { return "asteroids break apart"; }
}
public class Main {
public static void main(String[] args) {
Body[][] pairs = {
{new Ship(), new Asteroid()},
{new Asteroid(), new Ship()},
{new Asteroid(), new Asteroid()},
{new Ship(), new Ship()},
};
for (Body[] p : pairs) {
System.out.println(p[0].name() + " + " + p[1].name() + ": " + p[0].collide(p[1]));
}
}
}
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
- Verdict: idiom. The first call dispatches on the receiver, and the callback dispatches on the argument. The callbacks have different names, so no overload is chosen from a static type.
using System;
interface IBody
{
string Name { get; }
string Collide(IBody other);
string CollideWithShip(Ship ship);
string CollideWithAsteroid(Asteroid asteroid);
}
class Ship : IBody
{
public string Name => "ship";
public string Collide(IBody other) => other.CollideWithShip(this);
public string CollideWithShip(Ship ship) => "ships bounce";
public string CollideWithAsteroid(Asteroid asteroid) => "ship takes damage";
}
class Asteroid : IBody
{
public string Name => "asteroid";
public string Collide(IBody other) => other.CollideWithAsteroid(this);
public string CollideWithShip(Ship ship) => "ship takes damage";
public string CollideWithAsteroid(Asteroid asteroid) => "asteroids break apart";
}
class Program
{
static void Main()
{
var pairs = new (IBody, IBody)[]
{
(new Ship(), new Asteroid()),
(new Asteroid(), new Ship()),
(new Asteroid(), new Asteroid()),
(new Ship(), new Ship()),
};
foreach (var (a, b) in pairs)
{
Console.WriteLine($"{a.Name} + {b.Name}: {a.Collide(b)}");
}
}
}
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
- Verdict: idiom. This is the classic form with an interface. C# can also cast the argument to
dynamic, which gives multiple dispatch without the callbacks.
class Ship {
get name() { return "ship"; }
collide(other) { return other.collideWithShip(this); }
collideWithShip(ship) { return "ships bounce"; }
collideWithAsteroid(asteroid) { return "ship takes damage"; }
}
class Asteroid {
get name() { return "asteroid"; }
collide(other) { return other.collideWithAsteroid(this); }
collideWithShip(ship) { return "ship takes damage"; }
collideWithAsteroid(asteroid) { return "asteroids break apart"; }
}
const pairs = [
[new Ship(), new Asteroid()],
[new Asteroid(), new Ship()],
[new Asteroid(), new Asteroid()],
[new Ship(), new Ship()],
];
for (const [a, b] of pairs) {
console.log(`${a.name} + ${b.name}: ${a.collide(b)}`);
}
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
- Verdict: idiom. A method call dispatches on the receiver, so
collidecalls back the other object with a method named for its own class.
interface Body {
name: string;
collide(other: Body): string;
collideWithShip(ship: Ship): string;
collideWithAsteroid(asteroid: Asteroid): string;
}
class Ship implements Body {
name = "ship";
collide(other: Body): string { return other.collideWithShip(this); }
collideWithShip(_ship: Ship): string { return "ships bounce"; }
collideWithAsteroid(_asteroid: Asteroid): string { return "ship takes damage"; }
}
class Asteroid implements Body {
name = "asteroid";
collide(other: Body): string { return other.collideWithAsteroid(this); }
collideWithShip(_ship: Ship): string { return "ship takes damage"; }
collideWithAsteroid(_asteroid: Asteroid): string { return "asteroids break apart"; }
}
const pairs: [Body, Body][] = [
[new Ship(), new Asteroid()],
[new Asteroid(), new Ship()],
[new Asteroid(), new Asteroid()],
[new Ship(), new Ship()],
];
for (const [a, b] of pairs) {
console.log(`${a.name} + ${b.name}: ${a.collide(b)}`);
}
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
- Verdict: idiom. The interface
Bodylists one callback method for each class, and each class implements all of them.
package main
import "fmt"
type Body interface {
Name() string
Collide(other Body) string
CollideWithShip(s Ship) string
CollideWithAsteroid(a Asteroid) string
}
type Ship struct{}
func (Ship) Name() string { return "ship" }
func (s Ship) Collide(other Body) string { return other.CollideWithShip(s) }
func (Ship) CollideWithShip(Ship) string { return "ships bounce" }
func (Ship) CollideWithAsteroid(Asteroid) string { return "ship takes damage" }
type Asteroid struct{}
func (Asteroid) Name() string { return "asteroid" }
func (a Asteroid) Collide(other Body) string { return other.CollideWithAsteroid(a) }
func (Asteroid) CollideWithShip(Ship) string { return "ship takes damage" }
func (Asteroid) CollideWithAsteroid(Asteroid) string { return "asteroids break apart" }
func main() {
pairs := [][2]Body{{Ship{}, Asteroid{}}, {Asteroid{}, Ship{}}, {Asteroid{}, Asteroid{}}, {Ship{}, Ship{}}}
for _, p := range pairs {
fmt.Printf("%s + %s: %s\n", p[0].Name(), p[1].Name(), p[0].Collide(p[1]))
}
}
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
- Verdict: idiom. Go has no overloading, so each callback has its own name. Another form is a type switch on both values.
trait Body {
fn name(&self) -> &'static str;
fn collide(&self, other: &dyn Body) -> &'static str;
fn collide_with_ship(&self) -> &'static str;
fn collide_with_asteroid(&self) -> &'static str;
}
struct Ship;
struct Asteroid;
impl Body for Ship {
fn name(&self) -> &'static str { "ship" }
fn collide(&self, other: &dyn Body) -> &'static str { other.collide_with_ship() }
fn collide_with_ship(&self) -> &'static str { "ships bounce" }
fn collide_with_asteroid(&self) -> &'static str { "ship takes damage" }
}
impl Body for Asteroid {
fn name(&self) -> &'static str { "asteroid" }
fn collide(&self, other: &dyn Body) -> &'static str { other.collide_with_asteroid() }
fn collide_with_ship(&self) -> &'static str { "ship takes damage" }
fn collide_with_asteroid(&self) -> &'static str { "asteroids break apart" }
}
fn main() {
let pairs: [(&dyn Body, &dyn Body); 4] =
[(&Ship, &Asteroid), (&Asteroid, &Ship), (&Asteroid, &Asteroid), (&Ship, &Ship)];
for (a, b) in pairs {
println!("{} + {}: {}", a.name(), b.name(), a.collide(b));
}
}
ship + asteroid: ship takes damage
asteroid + ship: ship takes damage
asteroid + asteroid: asteroids break apart
ship + ship: ships bounce
- Verdict: idiom. Trait objects dispatch on the receiver, so
collidecalls back the other trait object. Another form, for a closed set of types, is an enum and onematchon the pair(a, b).
Consequences
The benefits:
- The choice of computation depends on the run-time types of both arguments, with no type tests in the client.1
The costs:
- Run-time cost. The call has the usual costs of dynamic resolution, usually more than in a language with single dispatch only.1
- Many methods. In the example, each class has one callback method for each class that it can meet. A third class, such as a space station, adds a callback method to each existing class.
- Order. The two objects of a call have different roles. In the example,
ship + asteroidandasteroid + shipmust give the same result, so two methods must agree.
When not to use it
- The language has multiple dispatch, for example CLOS.1 Then one method can be declared for each pair of types.
- In C#, a call can do multiple dispatch without the Visitor pattern: the method uses traditional polymorphism and casts the argument to
dynamic.1 - Only one of the two types varies. Then single dispatch on that object is sufficient.
Variants and related patterns
- Visitor. The problem of the C++ example can be resolved by simulating double dispatch, for example with the Visitor pattern.1
- Reflected operators in Python. To evaluate
x - y, Python callstype(y).__rsub__(y, x)iftype(x).__sub__(x, y)returnsNotImplemented, or iftype(y)is a subclass oftype(x).3 So a binary operator can dispatch first on the left operand and then on the right operand:
class Meters:
def __init__(self, n):
self.n = n
def __add__(self, other):
if isinstance(other, Meters):
return Meters(self.n + other.n)
if isinstance(other, int):
return Meters(self.n + other)
return NotImplemented
__radd__ = __add__
def __repr__(self):
return f"Meters({self.n})"
print(Meters(2) + 3) # Meters.__add__
print(3 + Meters(2)) # int.__add__ returns NotImplemented, then Meters.__radd__
print(sum([Meters(1), Meters(2)])) # sum starts with 0 + Meters(1)
Meters(5)
Meters(5)
Meters(3)
Known uses
- Dan Ingalls described double dispatching in Smalltalk in 1986.1
- CPython's
fractions.Fractionmakes its arithmetic operators with_operator_fallbacks, which returns a forward and a reverse function. The comment says that mixed-mode operations should "call an implementation whose author knew about the types of both arguments", or convert both to the nearest built in type. The functions returnNotImplementedfor types that they do not know.4
References
- Double dispatch, Wikipedia, Introduction; Overview; Use cases; A common idiom; Examples, C++ and C#
- The Python Standard Library, functools, functools.singledispatch, functools.singledispatch
- The Python Language Reference, 3.3.8 Emulating numeric types, object.__radd__ and the other reflected methods
- CPython v3.14.0 source, Lib/fractions.py, Fraction._operator_fallbacks, forward and reverse, lines 616 to 724
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag VEMJGW Edit this page History Report an error Markdown