liveBook · Manning

Multimethod

As explained in Data-Oriented Programming: Reduce software complexity

A multimethod method is a function that provides an implementation for a particular dispatch value.

A multimethod provides polymorphism without requiring objects. It combines a dispatch function, which emits a dispatch value, with methods that implement behavior for particular dispatch values. section 13.2 section 13.6

The dispatch function gives the multimethod its behavioral shape:

  • Defines the function signature and receives the same arguments passed to the selected method. section 13.6
  • Validates arguments, using schemas when development checks are enabled. section 13.2 section 13.3
  • Emits a value such as an animal type, a pair of argument types, or a type combined with a runtime Boolean. section 13.2 section 13.4
  • Selects the matching method, while a default method can handle otherwise-unmatched values. section 13.2 section 13.6

Formatting an author name

A production-style formatter dispatches on an author's prolificity level—low, medium, or high—and a requested format—HTML or Markdown. Low authors receive italic text, medium authors bold text, and high authors bold italic text. The multimethod is then called like an ordinary function: Author.myName(author, "html") or Author.myName(author, "markdown"). section 13.5

Listing 13.6 The dispatch function for greet multimethod
function greetDispatch(animal) {                     #1
  if(dev()) {
    if(!ajv.validate(animalSchema, animal)) {        #2
      var errors = ajv.errorsText(ajv.errors);
      throw ("greet called with invalid arguments: " + errors);
    }
  }
 
  return animal.type;                                #3
}
 
var greet = multi(greetDispatch);                    #4

Inspect the dispatch function that validates an animal, emits its type, and initializes the greet multimethod. section 13.2

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Explains dispatch responsibilities, validation, method wiring, defaults, and three dispatch forms through JavaScript examples.
Examples
Demonstrates animal greetings, multilingual animal greetings, name-length behavior, and author-name formatting.
What it assumes
Assumes functions and generic maps while teaching polymorphism without objects from the dispatch-function model upward.
What you can do after
Build it from scratch by defining a dispatch function, initializing a multimethod, wiring implementations, and calling it as a regular function.
How it connects
Connects polymorphism with OOP inheritance, multiple dispatch, dynamic dispatch, generic maps, and extensibility.

Also explained in

Compare how 2 books explain multimethod →

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.