liveBook · Manning

Multi

As explained in Data-Oriented Programming: Reduce software complexity

multi is a library function that creates a multimethod.

When animal behavior varies by type, multi creates a multimethod: a callable function whose dispatch function selects the matching implementation without requiring objects. section 13.2

A multimethod combines:

  • A dispatch function that receives the arguments and returns a dispatch value such as "dog", "cat", or "cow". section 13.2
  • Methods registered for particular dispatch values, plus an optional default implementation. section 13.2

Greeting animals

Create greet with multi(greetDispatch), register greetDog, greetCat, and greetCow, then call greet(myDog), greet(myCat), or greet(myCow) like a regular function. A default method handles an unfamiliar horse. section 13.2

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 and the point where multi creates greet. section 13.2

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Explains dispatch functions, registered methods, arguments, default handling, and calls, but does not descend into multi internals.
Examples
Demonstrates dog, cat, cow, and horse greeting methods selected from animal.type.
What you can do after
Build it from scratch by defining a dispatch function, creating a multimethod with multi, and registering implementations.
How it connects
Connects multi with multimethods, dispatch functions, methods, polymorphism, and single dispatch.

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.