Chapter 4: Domain Modeling with Algebraic Data Types
The chapter introduces an iterative design approach that focuses on domain data and its meaning before operational or system-level concerns.
After this chapter you will be able to
- Domain Data Representation. Explain why this design approach concentrates on what domain data means and how it is represented, while setting aside behavior, efficiency, and system tradeoffs for now.
- From vague requirements to code. Explain why the request to create and use checklists is only a starting point for a data model.
- Checklist templates and instances. Explain why a checklist model needs to distinguish a reusable template for work from an instance that someone runs through, rather than starting with a list of checkboxes.
- Templates and checklist instances. Distinguish a reusable checklist template from an instance used to carry it out, and describe why engineers create templates.
- Completed checklists as records. Explain why engineers keep completed checklist instances rather than resetting or discarding them.
- Iterative meaning driven modeling. Explain how the section uses provisional code sketches and repeated checks against domain meaning to develop a model.
- Template and completion separation. Explain why completion does not belong in a template’s Step and why the section removes isCompleted rather than sanitizing it defensively.
- Status identity and instance context. Describe why a status must identify both its Step and its checklist Instance, and why the status need not be nested inside the Instance model.
- Completion-dependent audit attributes. Explain why the user and time of completion differ from a Step’s other attributes and why adding them as nullable fields changes the model’s meaning.
- Invalid states and construction guards. Describe the invalid states introduced by the nullable audit fields and what construction-time checks can and cannot repair.
- Auditable skipped-step requirements. Describe what must be recorded when a workflow step is skipped, and explain why adding fields to the existing model may be premature.
- DRY Refactoring Versus Meaning. Explain why factoring out similar attributes and replacing two Booleans with an enum reduces duplication without fixing the underlying model.
- Cost of Lost Data Meaning. Describe how a poorly modeled data type imposes defensive checks beyond its constructor, and why adding small fields for new requirements can worsen the problem.
- Implicit AND in records. Explain that a record presents its attributes together as an implicit AND, which can combine attributes whose meanings do not belong together.
- Aligning status meanings. Describe why variable-name hints cannot repair the mismatch between the checklist data and its code, and state the distinction the model needs to express.
- Reading attribute combinations literally. Explain how to assess a proposed data type by reading its combined attributes as the Java compiler would, rather than relying on the type’s name or prose to supply meaning.
- Distinct checklist state types. Explain why adding completedBy to the template and step attributes points to Completed rather than a generic Status, and why other checklist states need their own types.
- Checklist status alternatives. Explain why NotStarted, Completed, and Skipped need a single canonical data type despite each status already being modeled individually.
- Interfaces as domain data types. Explain how an interface can tie related records together as alternatives of one domain data type, rather than serving only as a behavioral contract.
- Closed checklist status model. Explain that ChecklistStatus is limited to NotStarted, Completed, and Skipped, and why an interface that anyone can implement does not enforce that limit.
- Closed families of domain data. Explain why sealing a type can make a domain model more precise: it states which implementations are allowed and rules out unknown future ones.
- Algebraic view of Java types. Explain that records and sealed interfaces are Java implementations of algebraic data types, and that the algebra uses two operators, + and ×, to reason symbolically about types.
- Records as product types. Explain how a record combines component types with AND, and how the resulting type contains every combination of their values.
- Growth of possible states. Explain why adding attributes to a record can rapidly expand its possible states and create a model with many invalid states.
- Sum types as choices. Explain that a sum type represents a choice between types, giving a model OR semantics, and that Java represents this with a sealed interface.
- Composing AND and OR types. Explain that records provide product-type AND semantics while sealed interfaces provide sum-type OR semantics, and that combining these simple forms can build complex data structures.
- Meaning over notation. Explain why the symbols used for algebraic data types can change without changing the modeled meaning, and state the section's guiding question for a model.
- Symbolic laws for types. Explain how replacing concrete types with symbols lets you manipulate a data model as an algebraic expression, using laws such as commutativity and distributivity.
- Invariant-preserving model refactoring. Explain how the distributive law factors duplicated information out of the chapter’s domain model, producing a different Java representation with the same information and invariants.
- Design Beyond Language Features. Explain why modeling a domain as a family of data types remains valuable without sealed interfaces.
- Older Java Grouping Convention. Describe how to signal that related types are intended to act like a sealed family on older Java versions, and state the convention's limit.
- Meaningful Models and Illegal States. Explain how friction while writing code can reveal that a model expresses states the domain does not intend, and how comparing meanings helps correct it.
- Explicit AND Relationships. Explain why bringing implicit AND relationships to the surface helps guide data modeling.
- Records and Interfaces for OR. Describe how records and interfaces express a choice among different options, and how this differs from a simple enum.
What it builds on
- “What does it mean?” (chapter 3) · The emphasis on understanding what domain data means.
- Discovering more about your domain (chapter 3) · Assumes the need to discover how people actually use a domain concept.
- Enforce invariants during construction (chapter 3) · The earlier discussion of enforcing invariants during construction provides context for guarding this model’s constraints.
- Modeling Data and Values with Records (chapter 2) · Assumes familiarity with records as a way to represent data.
- Data = values + meaning (chapter 2) · Assumes that data carries meaning.
- Types denote sets of values (chapter 3) · Types can be viewed as sets of values.
- The importance of understanding meaning (chapter 3) · Understanding why the meaning of domain data matters.
Section by section
Introduction
The chapter introduces an iterative design approach that focuses on domain data and its meaning before operational or system-level concerns.
- Friction in Iterative Design: Explain why the chapter includes missteps and dead ends in its design walkthrough: noticing the friction caused by a poor design helps identify problems that can then be fixed.
Why it matters: A design's awkwardness can be a useful clue rather than merely a setback. - Domain Data Representation: Explain why this design approach concentrates on what domain data means and how it is represented, while setting aside behavior, efficiency, and system tradeoffs for now.
Why it matters: It explains why the chapter works on the shape and meaning of data before tackling the rest of the system.
Key terms: data-oriented design, friction, representation, domain data
4.1 Starting from Requirements
Introduces a rocket-manufacturing checklist as the example and frames the modeling task as turning a loose requirement into precise code.
- From vague requirements to code: Explain why the request to create and use checklists is only a starting point for a data model.
Why it matters: A broad request does not yet specify what the code must represent. - Importance of manufacturing checklists: Explain why checklists matter in the rocket-manufacturing example.
Why it matters: The example gives a practical reason to model checklists carefully.
Key terms: loose requirements statement, precise code, checklist, procedure
4.1.1 The Humble Checklist
A familiar checklist example shows why domain requirements should be clarified before choosing a data model.
- Checklist templates and instances: Explain why a checklist model needs to distinguish a reusable template for work from an instance that someone runs through, rather than starting with a list of checkboxes.
Why it matters: Clarifying how people use checklists prevents a plausible-looking design from missing the domain’s central distinction.
Key terms: checklist, repeatability, template, instances
4.1.2 Firming up loose requirements
The section clarifies the difference between reusable checklist templates and the completed checklist instances engineers retain as records.
- Templates and checklist instances: Distinguish a reusable checklist template from an instance used to carry it out, and describe why engineers create templates.
Why it matters: Separating the reusable definition from each use makes the checklist domain easier to model. - Completed checklists as records: Explain why engineers keep completed checklist instances rather than resetting or discarding them.
Why it matters: A completed checklist captures what actually happened, not just what the reusable template says to do.
Key terms: template, instance, instances, data, artifacts
4.1.3 Translating into a model
The section develops a checklist data model by repeatedly sketching types, checking what they mean, and revising them to avoid invalid states.
- Iterative meaning driven modeling: Explain how the section uses provisional code sketches and repeated checks against domain meaning to develop a model.
Why it matters: Checking the meaning conveyed by a sketch helps catch modeling mistakes before they become workarounds. - Template and completion separation: Explain why completion does not belong in a template’s Step and why the section removes isCompleted rather than sanitizing it defensively.
Why it matters: Putting completion in the right part of the model prevents invalid states instead of requiring code to clean them up. - Status identity and instance context: Describe why a status must identify both its Step and its checklist Instance, and why the status need not be nested inside the Instance model.
Why it matters: A separate status can track changing completion without confusing a reusable step with its state in one checklist instance. - Loose sketch and invariants: State what the example model leaves unchecked and why the section distinguishes that loose sketch from a model that guards its invariants.
Why it matters: The sketch communicates the main relationships, but unchecked assumptions still leave room for invalid data.
Key terms: model, meaning, records, Template, Step, Instance, isCompleted, bad states, Status, constraints
4.1.4 New Requirements: Keeping Track of Who Did What
A request to record who completed a checklist step and when exposes how nullable fields can obscure a Step’s meaning and create invalid states.
- Completion-dependent audit attributes: Explain why the user and time of completion differ from a Step’s other attributes and why adding them as nullable fields changes the model’s meaning.
Why it matters: A field that applies only in some states can make a seemingly simple data model misleading. - Invalid states and construction guards: Describe the invalid states introduced by the nullable audit fields and what construction-time checks can and cannot repair.
Why it matters: Validation can reject bad combinations without making the underlying data model self-explanatory.
Key terms: Step, nullable fields, data’s meaning, invalid states, defensive programming, construction, Status
4.1.5 Increasing complexity: another requirements change
A new workflow requirement adds skipped steps to the model and raises the need to understand and record why each step was skipped.
- Auditable skipped-step requirements: Describe what must be recorded when a workflow step is skipped, and explain why adding fields to the existing model may be premature.
Why it matters: The model needs to capture the reason for a consequential decision, not just reuse fields because they are convenient.
Key terms: skip individual steps, auditable trail, rationale
4.1.6 Beware of refactoring the code, rather than its meaning
This section shows why removing duplicated fields does not fix a domain model whose meaning depends on context, and how that flaw spreads defensive checks throughout the code.
- DRY Refactoring Versus Meaning: Explain why factoring out similar attributes and replacing two Booleans with an enum reduces duplication without fixing the underlying model.
Why it matters: Less code is not necessarily a better model if the same invalid combinations remain possible. - Cost of Lost Data Meaning: Describe how a poorly modeled data type imposes defensive checks beyond its constructor, and why adding small fields for new requirements can worsen the problem.
Why it matters: The cost of an unclear representation is paid wherever the data is used, not just when it is constructed.
Key terms: Don’t Repeat Yourself (DRY), contextual, illegal states, defensive code, meaning, nullable fields, null pointer exceptions
4.2 Records are tools for modelling “AND”
The section shows how a record’s implicit AND can obscure distinct checklist-status meanings and argues for aligning the code with the meaning of the data.
- Implicit AND in records: Explain that a record presents its attributes together as an implicit AND, which can combine attributes whose meanings do not belong together.
Why it matters: A record’s shape can imply a meaning the domain data does not support. - Aligning status meanings: Describe why variable-name hints cannot repair the mismatch between the checklist data and its code, and state the distinction the model needs to express.
Why it matters: Readers should be able to see the domain’s distinctions in the model rather than reconstruct them from naming clues.
Key terms: record, AND, semantic drift, completedOn/by, Status, meaning of our data, meaning of our code, checklist status, nullable attributes
4.2.1 Designing consciously with AND
The section uses the attributes of checklist statuses to show how consciously reading a record’s AND relationships leads to separate, more meaningful data types.
- Reading attribute combinations literally: Explain how to assess a proposed data type by reading its combined attributes as the Java compiler would, rather than relying on the type’s name or prose to supply meaning.
Why it matters: Reading what the attributes actually express helps expose a mismatch between a type’s name and its possible values. - Distinct checklist state types: Explain why adding completedBy to the template and step attributes points to Completed rather than a generic Status, and why other checklist states need their own types.
Why it matters: Giving each state only its meaningful attributes removes invalid states instead of requiring code to guard against them. - Meaning over implementation choice: State what matters most when translating this data model into Java, and why the section does not prescribe one official representation.
Why it matters: The reader can preserve the model’s meaning without treating this example’s Java code as the only valid solution.
Key terms: AND, attributes, Status, Completed, NotStarted, Skipped, illegal states, defensive validation, data model, implementation
4.3 Modeling “one of” relationships with OR
The section identifies the need to group distinct checklist-status records under one data type representing alternative statuses.
- Checklist status alternatives: Explain why NotStarted, Completed, and Skipped need a single canonical data type despite each status already being modeled individually.
Why it matters: It makes the relationship among the possible checklist statuses explicit in the model.
Key terms: Checklist Statuses, canonical data type, OR
4.3.1 Interfaces are data types
Shows how an interface and its implementing records can model a domain status with several possible forms, including forms that carry data.
- Interfaces as domain data types: Explain how an interface can tie related records together as alternatives of one domain data type, rather than serving only as a behavioral contract.
Why it matters: This lets the model state the possible forms of a status directly in its types. - Records beyond enum constants: Distinguish this interface-and-record setup from an enum by explaining what the records can carry.
Why it matters: It explains why the section uses records for status options instead of only enum constants.
Key terms: interface, records, ChecklistStatus, OR, Enums, attributes
4.4 Some data models should be closed to extension
This section explains why a domain model should allow only the states the domain recognizes, and why an open Java interface can fail to enforce that boundary.
- Closed checklist status model: Explain that ChecklistStatus is limited to NotStarted, Completed, and Skipped, and why an interface that anyone can implement does not enforce that limit.
Why it matters: Limiting the possible states lets you reason exhaustively about the domain. - Domain-driven extension choices: Justify choosing whether a model is extensible according to the domain rather than treating openness as an automatic benefit.
Why it matters: A model should express the states that matter to the application, not admit extras merely for flexibility.
Key terms: ChecklistStatus, NotStarted, Completed, Skipped, closed, interface, extensibility, domain
4.5 Representing Sealed Families of Data
The section shows how Java sealed types represent a closed family of domain data, including when the permits clause can be omitted.
- Closed families of domain data: Explain why sealing a type can make a domain model more precise: it states which implementations are allowed and rules out unknown future ones.
Why it matters: Closing a family lets the code express the boundaries of the domain concept. - Implicit permitted types: Describe when a sealed interface can omit its permits clause and how Java determines the permitted records in that case.
Why it matters: Putting the alternatives together can make their status as one closed family visible in one place.
Key terms: sealed, closed families of data, permitted, permits clause, interface's body
4.6 Algebraic Data Types
The section introduces Java records and sealed interfaces as implementations of algebraic data types that can be reasoned about symbolically.
- Algebraic view of Java types: Explain that records and sealed interfaces are Java implementations of algebraic data types, and that the algebra uses two operators, + and ×, to reason symbolically about types.
Why it matters: This perspective gives you another way to analyze and talk about Java data models.
Key terms: Algebraic Data Types, records, sealed interfaces, +, ×
4.6.1 Product Types
This section explains records as product types and shows how their possible states arise from combining the values of their component types.
- Records as product types: Explain how a record combines component types with AND, and how the resulting type contains every combination of their values.
Why it matters: It gives you a way to reason about what values a record can actually represent. - Growth of possible states: Explain why adding attributes to a record can rapidly expand its possible states and create a model with many invalid states.
Why it matters: It explains why simply adding fields can make a domain model harder to keep valid.
Key terms: records, Algebraic Product Types, AND, Cartesian product, possible states, invalid states, ANDing
4.6.2 Sum Types
This section explains sum types as OR-shaped choices represented by sealed interfaces in Java, and shows how they combine with product types to build larger data models.
- Sum types as choices: Explain that a sum type represents a choice between types, giving a model OR semantics, and that Java represents this with a sealed interface.
Why it matters: This gives you a way to recognize when a domain model calls for one alternative rather than several things together. - Counting sum type alternatives: Describe why the section calls these types sums: the count of choices is the sum of the types sealed under the interface.
Why it matters: Counting the alternatives makes the term “sum type” less abstract. - Composing AND and OR types: Explain that records provide product-type AND semantics while sealed interfaces provide sum-type OR semantics, and that combining these simple forms can build complex data structures.
Why it matters: These two building blocks let you express larger domain models from smaller types.
Key terms: Sum Types, OR semantics, sealed interfaces, sum, sealed interface, Product Types, AND semantics, Record Classes
4.6.3 What’s the point of knowing this stuff?
This section explains why algebraic data types are useful beyond Java syntax: they provide a shared vocabulary and a compact way to model meaning.
- Shared algebraic vocabulary: Explain how product and sum types let programmers discuss the same modeling patterns across languages, despite differences in syntax and implementation.
Why it matters: The algebra gives you terms for discussing a model without first translating every language-specific construct. - Compact modeling language: Describe why the section suggests using algebra to sketch a model instead of thinking entirely in Java code.
Why it matters: A compact sketch can help you consider a model before committing to Java declarations. - Meaning over notation: Explain why the symbols used for algebraic data types can change without changing the modeled meaning, and state the section's guiding question for a model.
Why it matters: Keeping meaning foremost lets you reason about a model independently of its notation or Java implementation.
Key terms: Product Types, Sum Types, sealed interface, underlying algebra, algebra, sketching, modeling, semantics, AND, OR
4.6.4 Refactoring domain models algebraically
The section shows how algebraic laws can reshape a domain model while preserving its information and invariants.
- Symbolic laws for types: Explain how replacing concrete types with symbols lets you manipulate a data model as an algebraic expression, using laws such as commutativity and distributivity.
Why it matters: These laws provide a way to reason about alternative shapes for the same data. - Type sizes and optionality: Describe how a literal number represents the number of values in a type, and how a one-value no-argument case combines with a type A to express optionality.
Why it matters: Counting a type’s possible values helps make alternatives such as absence explicit in a model. - Invariant-preserving model refactoring: Explain how the distributive law factors duplicated information out of the chapter’s domain model, producing a different Java representation with the same information and invariants.
Why it matters: The algebra lets you explore a less repetitive model without relying solely on intuition to preserve valid states.
Key terms: algebraic types, product types, sum types, commute, distribute, size, optionality, Empty(), Nothing(), distributive law
4.7 What to do if you you're on older versions of Java
The section explains how to signal a sealed-style family of data types on older Java versions without mistaking that convention for compiler enforcement.
- Design Beyond Language Features: Explain why modeling a domain as a family of data types remains valuable without sealed interfaces.
Why it matters: You can still make a useful domain model when your Java version lacks sealed interfaces. - Older Java Grouping Convention: Describe how to signal that related types are intended to act like a sealed family on older Java versions, and state the convention's limit.
Why it matters: The convention communicates design intent without promising a guarantee the compiler cannot provide.
Key terms: sum types, sealed interfaces, domain, related types, same file, sealed qualifier
4.8 Wrapping Up
This section draws together three domain-modeling lessons: align code with the meaning of the data, make implicit AND relationships explicit, and use records and interfaces to express OR choices.
- Meaningful Models and Illegal States: Explain how friction while writing code can reveal that a model expresses states the domain does not intend, and how comparing meanings helps correct it.
Why it matters: Noticing this friction helps you question the model instead of merely working around it. - Explicit AND Relationships: Explain why bringing implicit AND relationships to the surface helps guide data modeling.
Why it matters: Making AND relationships visible helps keep the shape of the data aligned with its meaning. - Records and Interfaces for OR: Describe how records and interfaces express a choice among different options, and how this differs from a simple enum.
Why it matters: This gives you a way to model a fixed set of alternatives without limiting each alternative to a simple enum value.
Key terms: illegal states, friction, meaning, implicit ANDs, data modeling, records, interfaces, OR, enum, runtime values
4.9 Summary
Where this is used later
- Modeling domain behaviors around data (chapter 5) · Modeling behaviors around data builds on the data-first emphasis introduced here.
- "Encouraging timely payments" (chapter 5) · Starting a domain model from requirements.
- Modeling domain behaviors around existing code (chapter 5) · Supplies earlier experience modeling domain data that the author proposes applying to behaviors.
- Represent runtime decisions as compile time algebraic data types (chapter 5) · Introduces algebraic data types for representing alternatives.
- Invariants, Properties, State, and an upside-down capital A (chapter 7) · Records as product types.
- Thinking Algebraically (chapter 7) · Develops algebraic reasoning in more detail.
- Optional as a parallel world (chapter 7) · Returns to Optional in algebraic reasoning.
Concepts explained in this chapter
- illegal stateAn illegal state is a program state that violates the validity constraints imposed by its data model or domain rules.
- data modelingData modeling is the design process of identifying domain information, its meaning, and its representation.
- semanticsSemantics are the intended meanings that a program expresses through its data and operations.
- union typeA sum type is a type formed by combining alternative types with OR semantics so that a value belongs to one of several permitted variants.
- algebraic data typeAn algebraic data type is a composite type whose values are formed by combining product and sum alternatives of other types.
- data typeA data type is a classification of data that determines its representation, permitted values, and valid operations.
- optionOptional is the Java container class that represents either a present non-null value or the absence of a value.
- product typeA product type is a type whose values combine one value from each of several component types, corresponding to logical AND and a Cartesian product.
- defensive programmingDefensive programming is a programming technique that anticipates invalid conditions and adds checks or safeguards to prevent their harmful effects.
- checklistA checklist is an ordered set of actionable items whose completion can be explicitly marked to control execution of a complex process.
- task instanceAn instance is a concrete occurrence of a template or checklist carried out during a particular activity.
- sealed typeA sealed Java type restricts which classes or interfaces may directly extend or implement it.
- refactoringRefactoring is the restructuring of existing software without changing its externally observable behavior.
- semantic driftSemantic drift is the gradual divergence of a program’s interpretation of data or state from its intended meaning.
- constraintA constraint is a condition that restricts which data representations or program states are valid.
- invariantAn invariant is a condition that must remain true across the valid states of a data structure or computation.
- attributeAn attribute is a named component of a data representation that describes one property of an entity or value.
- contextual attributeA contextual attribute is an attribute whose meaning applies specifically to a particular domain state or context rather than to the general concept.
- data-oriented programmingData-oriented programming is a programming approach that organizes software around explicit data representations and operations on those representations.
- algebraic operationAn algebraic operation is a rule for combining elements of specified sets to produce an element of a specified result set.
- missing valueA special Java reference value indicating the absence of an object rather than an instance of the referenced type.
- optionalityThe property of domain information that may be present or absent and whose absence has explicit meaning.
- dataData is information represented independently of the behaviors that operate on it.
- Cartesian productA Cartesian product is the set of all ordered tuples formed by choosing one element from each of several sets.
- requirementsA requirement is a stated condition or capability that a software system or process must satisfy.
- algebraic lawAn algebraic property is a characteristic describing how an operation behaves under operand order, grouping, and relationships between inputs and outputs.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
