liveBook · Manning

Case statement

As explained in Data-Oriented Programming: Reduce software complexity

A switch statement selects and executes code according to the value of an expression or discriminant.

A case statement selects behavior from a discriminant such as an animal's type. It can replace separate classes with data and one dispatching function, but changes then concentrate in that function. section 13.1

One greeting function, three cases

Represent a dog, cat, or cow as a map containing name and type, then switch on type to print the appropriate greeting. Invalid maps require explicit validation.

The design trade-off is straightforward:

  • Changing one animal's behavior requires editing the shared dispatching code, unlike changing a class implementation. section 13.1

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Demonstrates type dispatch, validation, and maintenance trade-offs, while stopping short of general switch semantics.
Examples
Uses dog, cat, and cow maps whose greetings are selected by their type fields.
What it assumes
Assumes basic functions and objects while introducing the comparison between maps with type fields and classes with methods.
What you can do after
Evaluate centralized case dispatch against separate polymorphic implementations and add validation for map-shaped inputs.
How it connects
Connects case statements to polymorphism, object-oriented programming, maps, and data validation.

Also explained in

Compare how 9 books explain case statement →

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.