liveBook · Manning

Multiple dispatch

As explained in Data-Oriented Programming: Reduce software complexity

Multiple dispatch is a dispatch mechanism that selects an implementation based on the types of several arguments.

Multiple dispatch selects an implementation from several arguments, extending polymorphism beyond object-oriented single dispatch. A dispatch function emits a value derived from those arguments, and methods implement matching cases. section 13.0 section 13.6

Greeting by animal and language

A greetLang multimethod dispatches on an animal type and a language type. Calling it with a dog and French selects French output; dog and English selects English output. The emitted array must keep the same order as the method wiring. section 13.3 section 13.3

Listing 13.15 Initializing a multimethod with a dispatch function
var greetLangArgsSchema = {
  "type": "array",
  "prefixItems": [animalSchema, languageSchema]
};
 
function greetLangDispatch(animal, language) {
  if(dev()) {
    if(!ajv.validate(greetLangArgsSchema, [animal, language])) {
      throw ("greetLang called with invalid arguments: " +
        ajv.errorsText(ajv.errors));
    }
  }
  return [animal.type, language.type];
};
 
var greetLang = multi(greetLangDispatch);

Inspect the dispatch function that validates arguments and emits the animal-language dispatch value. section 13.3

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Explains dispatch signatures, validation, emitted values, method wiring, calls, and ordering, while deferring dynamic dispatch.
Examples
Demonstrates animal greetings selected by dog, cat, or cow types combined with French or English language maps.
What it assumes
Assumes basic functions and maps while teaching multimethod structure, dispatch values, argument validation, and method registration.
What you can do after
Build it from scratch by defining a dispatch function, registering methods, and calling the multimethod like a regular function.
How it connects
Connects multiple dispatch with multimethods, polymorphism, single dispatch, dynamic dispatch, and object-oriented polymorphism.

Also explained in

Compare how 2 books explain multiple dispatch →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming: Reduce software complexity. The section links point to the parts of the book it draws on.