Chapter 6: Implementing the Domain Model
The chapter introduction explains why implementing the invoicing domain model requires care with Java methods and decisions about code organization.
After this chapter you will be able to
- Implementation risks to the model. Explain how an implementation can undermine a good data model when Java methods have unexpected side effects and force reasoning about too much of the program at once.
- Determinism through data separation. Explain how separating data acquisition from behavior makes the behavior deterministic: it takes data as input and returns data as output. Describe why the section treats that property as a useful design criterion.
- Deterministic input-output relationship. Explain that a mathematical function assigns the same output to the same input, with its output determined entirely by that input. Distinguish immutable instance state from environmental reads and mutable instance state in this account.
- Purity and observable effects. Distinguish purity from merely calculating a deterministic result: a pure function must also have no observable effects on the world. Explain why even a log statement makes a function impure.
- Determinism as design criterion. Explain how asking whether a function is deterministic can guide implementation choices. Describe why separating how data is obtained from what is done with it can make behavior easier to reason about and test.
- Static methods as purity signals. Explain why the author makes deterministic functions static in Java, how this discourages access to changing instance state, and why team discipline is still needed.
- Bounded Function Behavior. Explain why a pure, deterministic function has a more constrained set of possible behaviors than an impure function, and how that affects reasoning about its inputs and outputs.
- Separating Data Acquisition and Use. Explain how a program can make more of its work deterministic even though it must interact with the outside world.
- Local reasoning about functions. Explain why a function whose inputs are supplied as arguments and whose results are returned as outputs can be understood without tracing surrounding state.
- Functions as input-output mappings. Explain why a deterministic function can be viewed conceptually as a lookup table of inputs and predetermined outputs.
- Replacing computation with data. Explain why executing a deterministic function can be replaced by looking up or directly using its predetermined result, and why that helps with testing and debugging.
- Date-dependent grace period. Explain why a fixed number of days does not fully represent the grace-period rules, and describe grace period as a relationship between an input date and an output date.
- Rating-selected date function. Describe how a deterministic function can map a customer rating to another function that maps one point in time to another.
- Pragmatic determinism with identity objects. Explain why a function using data that depends on a mutable identity object is not strictly deterministic, and why the section recommends treating such inputs as data in practice.
- One-way core dependencies. Explain why the deterministic core cannot depend on the non-deterministic outer layer, and describe the resulting direction of dependencies.
- Deterministic core organization. Explain why deterministic business logic should have a consistent location and why the book puts it in a class called Core without requiring that structure.
- Type Guided Implementation. Explain how the type signature guides the implementation of collectPastDue and what decision it leaves to the filtering logic.
- Exhaustive Grace Period Cases. Distinguish a map lookup from case statements for grace periods, and explain why the section favors case statements when Rating enum values can change.
- Type Guided Draft Assembly. Explain how the designed types constrain the draft-building function, leaving fee and due-date calculations to plug in. Describe how a due-date option such as Net 60 maps to a number of days.
- Separated Fee Calculations. Describe how the fee calculation sums invoice line items and applies a percentage, and why the section separates summing from computing the fee.
- Unenforced Currency Assumption. Explain why blindly converting line-item currency to USD feels unsafe, despite the expectation that everything in the domain uses USD.
- USD invariant design feedback. Explain how representing invoices as USD in the data model exposes a mismatch with code that does not enforce that requirement elsewhere.
- Pragmatic response to invariant gaps. Describe the section’s response to a newly exposed invariant gap: call it out and defend against it now, without assuming the entire codebase must be fixed immediately.
- Draft assessment decisions. Explain how the draft total determines whether billing is blocked, allowed, or dependent on approval.
- Optional style and reader focus. Explain why the section chooses an imperative approach to a missing Approval over a functional Optional approach, without treating either style as universally correct.
- Explicit assessment cases. Explain why the assessment’s final case deserves an explicit name rather than an else branch, and when introducing another type helps.
- The non-deterministic sandwich. Describe how the main method surrounds the deterministic core with non-deterministic work, and explain the direction of the dependency.
- Predictable shell methods. Explain how the section says to keep methods disciplined after moving out of the deterministic core.
- Saving through existing types. Explain why the implementation transforms a LateFee into a type the existing system understands instead of saving LateFee directly.
- Invoice as an exchange point. Explain how Invoice connects the isolated domain model to the surrounding legacy system: outside code and persistence use Invoice Entity, while the new code treats it as a data transfer object and maps between the two worlds deterministically.
- Data as architectural interfaces. Explain how the domain model creates seams that let parts of the application be rearranged, and why deterministic main logic provides further options for how it runs.
- Determinism at Two Scales. Explain how determinism guided both the simplification of individual methods and the organization of the codebase in the Late Fees implementation.
What it builds on
- The finished data model (chapter 5) · The invoicing domain model developed before implementation begins.
- Separate how you get the data from what you do with it (chapter 5) · Introduces separating how data is obtained from what is done with it.
- Types denote sets of values (chapter 3) · Types viewed as sets of values.
- Capturing semantics in code (chapter 3) · Capturing domain semantics in code.
- “What does it mean?” (chapter 3) · The importance of understanding domain meaning.
- Enforce invariants during construction (chapter 3) · Encoding domain requirements in types and enforcing invariants.
- Fitting into what’s already there (chapter 5) · The need to fit new domain code into what already exists.
Section by section
Introduction
The chapter introduction explains why implementing the invoicing domain model requires care with Java methods and decisions about code organization.
- Implementation risks to the model: Explain how an implementation can undermine a good data model when Java methods have unexpected side effects and force reasoning about too much of the program at once.
Why it matters: This is why the chapter treats implementation choices as important even after the domain has been modeled. - Modeling before code ownership: Distinguish the earlier focus on data and its flow from the architectural choices that arise when implementing the model, such as which code owns behaviors and which parts can communicate.
Why it matters: It separates decisions already made in the data model from decisions still needed to organize the code.
Key terms: data model, methods, side-effects, class ownership, data, architectural choices
6.1 On the criteria by which we break down an implementation
Separating how data is obtained from what is done with it makes the behavior deterministic, providing a criterion for organizing the implementation.
- Determinism through data separation: Explain how separating data acquisition from behavior makes the behavior deterministic: it takes data as input and returns data as output. Describe why the section treats that property as a useful design criterion.
Why it matters: This gives you a reason to separate data-gathering work from behavior when organizing an implementation.
Key terms: deterministic, how we get data, what we do with it
6.1.1 Functions, Purity, and Determinism
This section distinguishes pure, deterministic mathematical functions from other Java methods and explains why that distinction helps organize code that is easier to reason about and test.
- Deterministic input-output relationship: Explain that a mathematical function assigns the same output to the same input, with its output determined entirely by that input. Distinguish immutable instance state from environmental reads and mutable instance state in this account.
Why it matters: This gives you a concrete way to tell whether a result can change without a change to the input. - Purity and observable effects: Distinguish purity from merely calculating a deterministic result: a pure function must also have no observable effects on the world. Explain why even a log statement makes a function impure.
Why it matters: A predictable return value alone does not mean a call leaves the rest of the world unchanged. - Determinism as design criterion: Explain how asking whether a function is deterministic can guide implementation choices. Describe why separating how data is obtained from what is done with it can make behavior easier to reason about and test.
Why it matters: This distinction helps you choose boundaries that reduce dependency-related reasoning and test setup.
Key terms: mathematical functions, deterministic, immutable instance state, purity, pure, impure, side-effects, determinism, dependencies
6.1.2 How do we write pure functions in Java?
This subsection presents static methods as a Java convention for signaling deterministic functions while acknowledging that static does not enforce purity.
- Static methods as purity signals: Explain why the author makes deterministic functions static in Java, how this discourages access to changing instance state, and why team discipline is still needed.
Why it matters: The convention makes deterministic intent visible without mistaking a Java modifier for a guarantee.
Key terms: purity, deterministic functions, static methods, instance state
6.1.3 The effect of deterministic functions on reasoning
This section explains how deterministic functions narrow the behaviors a function can express, making reasoning, testing, and composition easier while leaving interactions with the outside world separate.
- Bounded Function Behavior: Explain why a pure, deterministic function has a more constrained set of possible behaviors than an impure function, and how that affects reasoning about its inputs and outputs.
Why it matters: A smaller set of possible behaviors makes it easier to check what a function can do. - Composition of Deterministic Functions: Describe what happens when deterministic functions are combined and why the section presents this as a way to build larger behavior.
Why it matters: The benefit of deterministic functions can extend beyond individual methods to larger parts of a program. - Separating Data Acquisition and Use: Explain how a program can make more of its work deterministic even though it must interact with the outside world.
Why it matters: Outside-world interactions do not require the rest of a program’s logic to be non-deterministic.
Key terms: pure functions, deterministic functions, impure functions, inputs, outputs, combine functions, outside world, non-deterministic, deterministic, how you get data
6.1.4 Functions let you work locally
The section explains how functions that take all needed information as arguments make code and tests easier to understand locally.
- Local reasoning about functions: Explain why a function whose inputs are supplied as arguments and whose results are returned as outputs can be understood without tracing surrounding state.
Why it matters: You can follow the function's behavior without first building a mental map of surrounding state. - Input output focused tests: Describe how testing such a function centers on crafting inputs and checking expected outputs rather than orchestrating surrounding state.
Why it matters: The same local reasoning that simplifies reading a function can simplify its tests.
Key terms: mathematical functions, arguments, output, local reasoning, test setup, inputs, outputs
6.1.5 Functions are tables of immutable data in disguise
The section explains why a deterministic function can be viewed as immutable input-output data and why that equivalence is useful in testing and debugging.
- Functions as input-output mappings: Explain why a deterministic function can be viewed conceptually as a lookup table of inputs and predetermined outputs.
Why it matters: This view makes the relationship between functions and immutable data concrete. - Replacing computation with data: Explain why executing a deterministic function can be replaced by looking up or directly using its predetermined result, and why that helps with testing and debugging.
Why it matters: It explains why some computation can be set aside during testing or debugging without changing what the program does.
Key terms: determinism, lookup table, inputs and outputs, immutable data, pre-determined answer, secret state updates
6.1.6 Functions let us model relationships
The section models grace period as a date-to-date relationship selected by customer rating, rather than as a fixed number of days, and explains why naming that relationship matters.
- Date-dependent grace period: Explain why a fixed number of days does not fully represent the grace-period rules, and describe grace period as a relationship between an input date and an output date.
Why it matters: The date-dependent rule shows why a convenient numeric representation can miss the domain’s meaning. - Rating-selected date function: Describe how a deterministic function can map a customer rating to another function that maps one point in time to another.
Why it matters: Returning a function lets the code represent the date relationship without reducing it to a single scalar value. - Named domain concept: Justify giving gracePeriod its own named function even though applying the business rules directly to a date is also acceptable.
Why it matters: A name can preserve domain language and make the rule’s meaning visible to future readers of the code.
Key terms: grace period, input date, output date, fixed offset, CustomerRating, deterministic function, function type, gracePeriod, domain concept, domain language
6.1.7 One last note on all this deterministic business
This subsection explains why a data-oriented Java design can use practically deterministic code even when some data depends on mutable identity objects.
- Pragmatic determinism with identity objects: Explain why a function using data that depends on a mutable identity object is not strictly deterministic, and why the section recommends treating such inputs as data in practice.
Why it matters: This distinction lets you use deterministic-style reasoning without demanding impossible purity at every Java boundary.
Key terms: basically deterministic, actually deterministic, identity objects, data, mutable reference
6.2 Organizing code around determinism
The section uses determinism to divide the late-fee pipeline into a deterministic core and a non-deterministic outer layer, with dependencies flowing toward the core.
- Deterministic function classification: Distinguish pipeline functions that get everything they need from their inputs from functions that depend on service calls or other side effects.
Why it matters: This distinction gives you a practical starting point for organizing the pipeline's implementation. - One-way core dependencies: Explain why the deterministic core cannot depend on the non-deterministic outer layer, and describe the resulting direction of dependencies.
Why it matters: Keeping side-effecting dependencies out of the core preserves the property used to organize the code.
Key terms: deterministic, service calls, side effects, deterministic core, non-determinism, side-effects, functional core; imperative shell
6.3 Implementing the deterministic core
This section explains why the deterministic business logic should have a consistent, recognizable place in the code, while leaving its exact organization flexible.
- Deterministic core organization: Explain why deterministic business logic should have a consistent location and why the book puts it in a class called Core without requiring that structure.
Why it matters: A recognizable boundary helps you find the business logic without treating one file layout as mandatory.
Key terms: deterministic core, Core, deterministic business logic
6.3.1 Implementing collectPastDue
The section shows how the domain model narrows the implementation of collectPastDue, then explains why exhaustive case statements are safer than a map for grace periods.
- Type Guided Implementation: Explain how the type signature guides the implementation of collectPastDue and what decision it leaves to the filtering logic.
Why it matters: It shows how a well-defined model can simplify implementation without deciding every business rule. - Exhaustive Grace Period Cases: Distinguish a map lookup from case statements for grace periods, and explain why the section favors case statements when Rating enum values can change.
Why it matters: It explains why an elegant data representation can weaken guarantees when its possible keys may change.
Key terms: type signature, data types, filtering logic, gracePeriod, map, Rating enums, case statements, exhaustiveness, compile time guarantees
6.3.2 Implementing BuildDraft
This section implements draft late-fee calculations and exposes a currency assumption that the domain model does not enforce.
- Type Guided Draft Assembly: Explain how the designed types constrain the draft-building function, leaving fee and due-date calculations to plug in. Describe how a due-date option such as Net 60 maps to a number of days.
Why it matters: The model makes the implementation easier to follow by narrowing what the draft-building function can do. - Separated Fee Calculations: Describe how the fee calculation sums invoice line items and applies a percentage, and why the section separates summing from computing the fee.
Why it matters: Keeping the two calculations separate makes each step and its purpose easier to see. - Unenforced Currency Assumption: Explain why blindly converting line-item currency to USD feels unsafe, despite the expectation that everything in the domain uses USD.
Why it matters: An expectation about input data is not a guarantee when the model does not enforce it.
Key terms: draft, types, due dates, Net 60, line items, fee, percentage, functions, USD, original modeling
6.3.3 That really gross wrong feeling is a feature
An invoice’s USD type exposes a gap in where the application enforces that invariant, and the section argues for defending against the gap without fixing the whole codebase at once.
- USD invariant design feedback: Explain how representing invoices as USD in the data model exposes a mismatch with code that does not enforce that requirement elsewhere.
Why it matters: An uncomfortable mismatch between types and implementation can be useful feedback about the design. - Pragmatic response to invariant gaps: Describe the section’s response to a newly exposed invariant gap: call it out and defend against it now, without assuming the entire codebase must be fixed immediately.
Why it matters: You can use design feedback to improve a codebase without treating every discovered gap as an immediate rewrite.
Key terms: USD data type, invariant, type system, friction, front door
6.3.4 Implementing Assess Draft
This section explains how draft assessment uses the draft total to decide whether to bill and why the assessment must account for an approval that may not exist.
- Draft assessment decisions: Explain how the draft total determines whether billing is blocked, allowed, or dependent on approval.
Why it matters: These branches define the decision the draft-assessment function must make. - Possibly absent approvals: Explain why draft assessment cannot assume every customer has an Approval.
Why it matters: The approval-dependent decision must allow for there being no approval.
Key terms: draft, allowed range, Approval, created lazily, Optional
6.3.5 Dealing with optional
This section argues that Optional code should be chosen for what it communicates to readers, not for allegiance to an imperative or functional style.
- Optional style and reader focus: Explain why the section chooses an imperative approach to a missing Approval over a functional Optional approach, without treating either style as universally correct.
Why it matters: Choosing code by what it makes clear helps readers notice the important domain behavior.
Key terms: Optional, Approval, imperative, functional, orElse
6.3.6 It’s always OK to introduce more types!
This section shows how naming each assessment case with a type can clarify a domain decision that an if/else chain leaves implicit.
- Explicit assessment cases: Explain why the assessment’s final case deserves an explicit name rather than an else branch, and when introducing another type helps.
Why it matters: An explicit name lets a reader see the domain meaning that a catch-all else branch hides. - Decision and action separation: Describe the refactoring move of separating the assessment decision from what the program does with its result.
Why it matters: Separating the decision from its use helps readers focus on what each assessment case means.
Key terms: Assessment, else, types, main function, refactorings
6.4 Implementing the non-deterministic shell
This section explains how to connect a deterministic core to non-deterministic work while keeping the surrounding methods predictable.
- The non-deterministic sandwich: Describe how the main method surrounds the deterministic core with non-deterministic work, and explain the direction of the dependency.
Why it matters: This arrangement lets the core do its work without depending on data loading or saving. - Predictable shell methods: Explain how the section says to keep methods disciplined after moving out of the deterministic core.
Why it matters: A constrained, unsurprising shell remains easier to follow even when it performs side effects.
Key terms: non-deterministic work, deterministic core, sandwich, type signature, functions, pattern match
6.4.1 Who owns the save logic?
This subsection chooses a practical way to save a LateFee without making the existing persistence system understand the new domain type.
- Saving through existing types: Explain why the implementation transforms a LateFee into a type the existing system understands instead of saving LateFee directly.
Why it matters: This choice preserves the new domain model without requiring an immediate overhaul of the existing save logic.
Key terms: LateFee, Invoice, data-oriented, save
6.4.2 Treat legacy Entities as Data Transfer Objects
This subsection shows how to connect a new domain model to legacy persistence by treating the existing Invoice Entity as a data transfer object.
- Invoice as an exchange point: Explain how Invoice connects the isolated domain model to the surrounding legacy system: outside code and persistence use Invoice Entity, while the new code treats it as a data transfer object and maps between the two worlds deterministically.
Why it matters: This boundary lets the new model coexist with code that still expects Invoice Entity. - Value of boundary translation: Justify the tedious translation code: it gives the new domain model room to evolve independently while translation back to Invoice Entity preserves access to existing persistence machinery.
Why it matters: The translation makes incremental change possible in a legacy codebase.
Key terms: Invoice Entity, Data Transfer Object, deterministically map, semantic domain type, generic Invoice Entity, existing machinery, repositories
6.5 Data is the ultimate interface
The section explains how well-formed data and deterministic logic make it easier to change an application's architecture when a sequential for-loop is no longer sufficient.
- Data as architectural interfaces: Explain how the domain model creates seams that let parts of the application be rearranged, and why deterministic main logic provides further options for how it runs.
Why it matters: The model can support changes in execution and deployment without requiring every concern to remain in one sequential loop.
Key terms: data types, seams, natural interfaces, deterministic
6.6 Putting it all together
6.7 Wrapping up
The section identifies determinism as the guiding idea behind implementing the Late Fees data model.
- Determinism at Two Scales: Explain how determinism guided both the simplification of individual methods and the organization of the codebase in the Late Fees implementation.
Why it matters: It connects the chapter’s method-level choices to its overall code organization.
Key terms: determinism, Late Fees data model
6.8 Summary
Where this is used later
- Every possible state? Surely too inefficient to be practical! (chapter 7) · The discussion of checking possible states builds on the idea that a constrained set of behaviors can sometimes be exhausted.
- Use data to show what’s under test (chapter 11) · Applies the idea of showing what is under test through data.
- Data orientation makes tests better (chapter 11) · Provides a reason data orientation can make testing easier.
- Designing objects with functional core; imperative shell (chapter 10) · Organizing code around determinism
- Noticing algebraic operations in every day code (chapter 7) · Uses the implemented domain behavior as the code being reconsidered.
- Keep mutation where useful, but use it to build data (chapter 9) · treating legacy Entities as data transfer objects
- Draw boundaries with data (chapter 9) · Drawing boundaries with data applies the same approach to legacy-code refactoring.
Concepts explained in this chapter
- functionA computation that maps input values to an output value or values without requiring mutation of the input values.
- determinismA deterministic function is a computation whose output is completely determined by its inputs and remains consistent for repeated evaluations with those inputs.
- pure functionA pure function is a computation that produces the same output for the same inputs without observable side effects or dependence on mutable external state.
- nondeterminismNon-determinism is the property that identical inputs can produce different outputs because of hidden mutable state or other varying conditions.
- impure functionAn impure function is a function whose behavior can depend on external state or produce observable side effects beyond its returned result.
- type signatureA declaration of the types associated with a callable's inputs and output or another typed program element.
- 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.
- side effectA side effect is an observable change or interaction caused by a computation beyond producing its returned result.
- data transfer objectA data transfer object is a data-carrying structure used to exchange information between software components without encapsulating domain behavior.
- functional coreThe deterministic core is the central part of an application containing domain logic whose results do not depend on side effects or nondeterministic interactions.
- data transformationData transformation is the process of producing successive data states by changing or converting an existing representation.
- imperative shellAn architectural pattern that isolates deterministic computation in a functional core and places side effects and nondeterministic interactions in an imperative shell.
- invariantAn invariant is a condition that must remain true across the valid states of a data structure or computation.
- decision makingA decision is a modeled choice among alternative outcomes or actions based on available information.
- local reasoningA reasoning technique that determines a computation's behavior from its locally visible inputs, outputs, and dependencies.
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.
