liveBook · Manning

Dynamic dispatch

As explained in Data-Oriented Programming: Reduce software complexity

Dynamic dispatch is runtime selection of an operation implementation based on runtime argument information rather than only static types.

Dynamic dispatch selects a multimethod implementation from runtime argument information, not only static types. The dispatch function can emit values such as numbers or Booleans, enabling polymorphism without objects. section 13.0 section 13.4

A dynamic multimethod separates selection from implementation:

  • The dispatch function receives and validates the arguments. section 13.6
  • It emits a composite value based on runtime data. section 13.4
  • Methods implement each emitted value and remain extensible independently of initialization. section 13.6

Greeting animals by type and name length

The dysGreet dispatch function returns [animal.type, animal.name.length > 5]. Separate dog, cat, and cow methods then produce different greetings for long and short names; a cow named Clarabelle is greeted with “Moo! Call me Clarabelle.” section 13.4 section 13.6

Listing 13.18 A multimethod using a dispatch function with dynamic dispatch
function dysGreetDispatch(animal) {
  if(dev()) {
    if(!ajv.validate(animalSchema, animal)) {
      var errors = ajv.errorsText(ajv.errors);
      throw ("dysGreet called with invalid arguments: " + errors);
    }
  }
  var hasLongName = animal.name.length > 5;
 
  return [animal.type, hasLongName];
};
 
var dysGreet = multi(dysGreetDispatch);

Inspect the JavaScript dispatch function that validates an animal and emits the type-and-name-length dispatch value. section 13.4

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Explains dispatch functions, validation, emitted values, method wiring, defaults, and testing through a complete example.
Examples
Demonstrates dysGreet with dog, cat, and cow maps, combining animal type with whether a name exceeds five letters.
What it assumes
Assumes JavaScript functions and data maps while introducing polymorphism without object classes.
What you can do after
Build it from scratch with a dispatch function and methods keyed by runtime values.
How it connects
Connects dynamic dispatch to multimethods, polymorphism, single dispatch, multiple dispatch, generic maps, and extensibility.

Also explained in

Compare how 2 books explain dynamic 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.