Chapter 3: Building the domain core
The introduction argues that WriteFlow’s migration should begin with a framework-independent domain core whose business rules prevent invalid states.
After this chapter you will be able to
- Business Concepts Before Infrastructure. Explain why the migration starts with the business concepts the system cannot afford to get wrong, rather than with databases, adapters, APIs, or frameworks.
- Rules Enforced at Construction. Explain the chapter’s central aim of enforcing business rules when domain objects are constructed, so invalid states cannot exist and rules stay in one place.
- Domain inclusion criterion. Explain how to decide whether a concept belongs in the domain layer by asking whether it expresses a business rule or invariant independent of deployment and frameworks.
- Domain building block distinctions. Distinguish entities, value objects, and aggregates using the Article, Title, and Article aggregate examples.
- Framework-free domain boundary. Describe the domain as the innermost, framework-free layer and explain how it stays separate from outside layers.
- Explicit domain behavior. Explain why the domain favors immutable state, explicit inputs and outputs, and visible failures over step-by-step mutation, setters, and assumed external validation.
- Always-valid domain guarantee. Explain why a domain object must never exist while violating a business rule, even temporarily, and what callers can assume when an Article exists.
- Validated factory construction. Describe how a private constructor and a validating factory method prevent invalid domain objects from being created.
- Post-construction validation gap. Explain why creating an Article and then calling isValid fails to keep the domain model always valid.
- Handler-owned business rules. Explain why checking an Article title in a handler before construction is insufficient, despite preventing that handler from creating an invalid entity.
- Domain and framework construction. Describe why the domain should expose a factory method that validates invariants before calling a private constructor, rather than relying on constructor validation when frameworks also shape the class.
- Validated Article construction. Explain how a private constructor and validateThenCreate factory prevent callers from creating an Article without checking its invariants.
- Combined field validation. Trace how individual field checks are combined to create an Article or return multiple errors, and distinguish this behavior from Either.
- Separate validation and construction. Explain how canBeCreated lets a handler validate before constructing an Article, and why this leaves a gap in the validity guarantee.
- Constructor validation trade-off. Distinguish exception-based constructor validation from validateThenCreate, and explain why the book chooses the latter.
- Records and validated construction. Explain why this section recommends regular classes rather than Java records for domain entities that require validation, and identify when records are suitable.
- Explicit domain value types. Explain how replacing raw types such as String titles with value objects prevents scattered validation and makes method signatures clearer and type-safe. Distinguish why constructor validation suits value objects even though entities may need a controlled creation path.
- Domain service responsibilities. Explain when a domain service is appropriate and how it differs from an application service, using WriteFlow's slug-uniqueness rule as an example.
- Entity and standalone factories. Distinguish when to use an entity-level factory method such as Article.validateThenCreate and when to use a standalone factory class.
- Construction and validation responsibilities. Explain how a standalone factory coordinates creation without taking validation ownership from the entity, and describe the limits on its responsibilities.
- In-scope identity creation. Explain why an entity needs an identity at construction and how an application-generated UUID meets that requirement. State that WriteFlow uses this approach rather than repository-generated IDs.
- Repository-supplied identity. Explain the construction problem posed by infrastructure-generated IDs and how obtaining the next identity from a repository before construction addresses it.
- Input and business validation. Distinguish syntactic input validation from semantic business invariant validation by describing what each checks, where each belongs, and why invalid user input differs from a business rule violation.
- Validation ownership across layers. Trace validation in the article-creation request from REST adapter through command and domain entity, and explain why the handler and repository do not repeat checks owned by those layers.
- Command and domain validation boundaries. Distinguish input validation in commands from business validation in the domain, and describe the handler’s separate orchestration role.
- Syntactically valid command construction. Explain how CreateArticleCommand.validate(...) controls command creation and what the primary adapter does with its result.
- Guard Clause Purpose. Explain how guard clauses handle unmet preconditions and why they make validation logic easier to read.
What it builds on
- Phase 1: Extract the domain (chapter 2) · The migration’s Extract the domain phase.
- How a request travels through the hexagon (chapter 2) · The domain's place within the hexagon.
Section by section
Introduction
The introduction argues that WriteFlow’s migration should begin with a framework-independent domain core whose business rules prevent invalid states.
- Business Concepts Before Infrastructure: Explain why the migration starts with the business concepts the system cannot afford to get wrong, rather than with databases, adapters, APIs, or frameworks.
Why it matters: It helps you decide where to begin when an approved migration still feels risky. - Rules Enforced at Construction: Explain the chapter’s central aim of enforcing business rules when domain objects are constructed, so invalid states cannot exist and rules stay in one place.
Why it matters: Construction-time rules make the domain’s correctness a property of its objects, not a task left to callers.
Key terms: Phase 1—Extract the domain, business core, domain, business invariants, invalid states, construction time
3.1 What lives inside the domain layer
This section defines what belongs in the domain core, introduces its main DDD building blocks, and explains why domain objects stay behind its boundary.
- Domain inclusion criterion: Explain how to decide whether a concept belongs in the domain layer by asking whether it expresses a business rule or invariant independent of deployment and frameworks.
Why it matters: This test keeps technical concerns from being mistaken for domain rules. - Domain building block distinctions: Distinguish entities, value objects, and aggregates using the Article, Title, and Article aggregate examples.
Why it matters: These distinctions clarify what the domain models and how its parts relate. - Framework-free domain boundary: Describe the domain as the innermost, framework-free layer and explain how it stays separate from outside layers.
Why it matters: Keeping the core independent makes its rules quick to test and portable across infrastructure.
Key terms: domain layer, business rule, invariant, infrastructure, entities, value objects, aggregates, ArticleId, Title, domain boundary
3.2 Three principles that shape the domain
This section explains why domain design borrows functional ideas and where to prioritize its guiding principles.
- Explicit domain behavior: Explain why the domain favors immutable state, explicit inputs and outputs, and visible failures over step-by-step mutation, setters, and assumed external validation.
Why it matters: Explicit behavior makes the domain easier to trust and test without relying on its surroundings. - Priority of domain principles: Describe where the section says to prioritize purity, encapsulation, and completeness, and give an example of a business invariant.
Why it matters: This keeps attention on the domain objects responsible for rules that must always hold.
Key terms: functional design, immutability, explicit inputs and outputs, return type, purity, encapsulation, completeness, entities, value objects, business invariants
3.3 The Always-Valid Domain Model
The section establishes that domain objects must be valid from the moment they exist and explains how controlled construction enforces that guarantee.
- Always-valid domain guarantee: Explain why a domain object must never exist while violating a business rule, even temporarily, and what callers can assume when an Article exists.
Why it matters: The guarantee removes a category of bugs caused by invalid domain objects. - Validated factory construction: Describe how a private constructor and a validating factory method prevent invalid domain objects from being created.
Why it matters: Restricting construction makes validity a property of every created object, rather than a check each caller must remember.
Key terms: Always-Valid Domain Model, Article, business rule, private constructor, factory method, invariants, error
3.3.1 What not to do: Validation after construction
This section explains why validating an Article after construction or in a handler fails to guarantee a valid domain model, and why domain creation should be separated from framework construction.
- Post-construction validation gap: Explain why creating an Article and then calling isValid fails to keep the domain model always valid.
Why it matters: A validation check cannot undo the risk of having already exposed an invalid entity. - Handler-owned business rules: Explain why checking an Article title in a handler before construction is insufficient, despite preventing that handler from creating an invalid entity.
Why it matters: A domain invariant should not depend on every handler remembering the same check. - Domain and framework construction: Describe why the domain should expose a factory method that validates invariants before calling a private constructor, rather than relying on constructor validation when frameworks also shape the class.
Why it matters: Separating framework needs from domain creation keeps validity rules at the domain boundary.
Key terms: isValid, Article, Application Service, handler, title validation, factory method, invariants, private constructor, persistence and serialization frameworks
3.3.2 The recommended approach: validateThenCreate
This section shows how a private constructor and a validateThenCreate factory make Article creation valid by construction, collect field errors, and keep validation out of the handler.
- Validated Article construction: Explain how a private constructor and validateThenCreate factory prevent callers from creating an Article without checking its invariants.
Why it matters: Putting validation in the creation path makes the domain responsible for its own rules. - Combined field validation: Trace how individual field checks are combined to create an Article or return multiple errors, and distinguish this behavior from Either.
Why it matters: The caller can see all invalid fields in one response rather than discovering them one at a time. - Handler and factory responsibilities: Describe what the handler does with the factory's result and why it converts Validation to Either for subsequent operations.
Why it matters: The handler can coordinate the work without duplicating the domain's validation rules. - Construction and testing payoff: Explain why the private constructor and validated factory make the Article's rules straightforward to test without infrastructure.
Why it matters: The domain can prove its creation rules with fast tests that need no application infrastructure.
Key terms: TryExecute pattern, validateThenCreate, private constructor, invariants, Always-Valid Domain Model, Validation, Validation.combine, ap, Seq<DomainError>, Either
3.3.3 An alternative: canBeCreated
This subsection compares separating validation from Article construction with validating in the constructor, and explains why the book favors explicit creation failures.
- Separate validation and construction: Explain how canBeCreated lets a handler validate before constructing an Article, and why this leaves a gap in the validity guarantee.
Why it matters: It shows the difference between a validation convention and a creation boundary the code enforces. - Constructor validation trade-off: Distinguish exception-based constructor validation from validateThenCreate, and explain why the book chooses the latter.
Why it matters: The choice determines whether callers handle expected creation failures as return values or exceptions.
Key terms: canBeCreated, Command-Query Separation, Article, validateThenCreate, explicit return type, exceptions, Architecture Decision Record
3.3.4 A note on records
Explains why Java records are unsuitable for domain entities whose construction must be controlled by validation, while remaining useful for simpler data types.
- Records and validated construction: Explain why this section recommends regular classes rather than Java records for domain entities that require validation, and identify when records are suitable.
Why it matters: Choosing a type that permits unchecked construction can undermine an entity’s validity guarantee.
Key terms: Java records, canonical constructor, Always-Valid Domain Model, validateThenCreate, @RequiredArgsConstructor(access = AccessLevel.PRIVATE)
3.4 Value objects: Making implicit concepts explicit
This section shows how value objects make domain concepts explicit, enforce their constraints at construction, and avoid the problems of using raw primitive types.
- Explicit domain value types: Explain how replacing raw types such as String titles with value objects prevents scattered validation and makes method signatures clearer and type-safe. Distinguish why constructor validation suits value objects even though entities may need a controlled creation path.
Why it matters: Explicit types put a concept’s meaning and validation in one place instead of leaving every caller to reconstruct them. - Related attributes and behavior: Describe how a value object can hold related attributes and domain behavior, using PublicationPeriod as the example.
Why it matters: Grouping related values lets one domain type own both their consistency rule and useful behavior. - Value equality and immutability: Explain the two defining properties of value objects: equality by content rather than identity, and immutability after creation.
Why it matters: These properties make value objects predictable to compare and safe to share without synchronization.
Key terms: Primitive Obsession, value object, constructor validation, type safety, PublicationPeriod, isActiveOn, business rule, Equality by value, Immutability, Java records
3.5 Domain services
This section explains when business rules belong in a domain service, how that differs from application orchestration, and why domain services are simple to test.
- Domain service responsibilities: Explain when a domain service is appropriate and how it differs from an application service, using WriteFlow's slug-uniqueness rule as an example.
Why it matters: It helps you put a business rule in the domain without forcing an entity to take on responsibilities outside its own state. - Slug uniqueness consistency guard: Explain why the domain service's slug-uniqueness rule does not by itself guarantee uniqueness under concurrent requests.
Why it matters: It separates expressing a business rule from guaranteeing consistency when requests race. - Direct domain service testing: Describe why the domain service can usually be instantiated and unit tested directly without an interface, mocks, dependency injection, or a Spring context.
Why it matters: Keeping domain rules free of infrastructure makes their tests small and fast to write.
Key terms: domain service, application service, aggregates, business rules, existing slugs, persistence boundary, database constraint, consistency guard, pure function, infrastructure dependencies
3.6 Factories
This section explains when to create an entity through its own factory method or a standalone factory, and how to keep construction and validation responsibilities separate.
- Entity and standalone factories: Distinguish when to use an entity-level factory method such as Article.validateThenCreate and when to use a standalone factory class.
Why it matters: The distinction helps you put construction logic where its dependencies belong. - Construction and validation responsibilities: Explain how a standalone factory coordinates creation without taking validation ownership from the entity, and describe the limits on its responsibilities.
Why it matters: This keeps creation in one place without bypassing the entity’s validation or mixing unrelated business logic into the factory.
Key terms: factory method, entity-level factory, standalone factory class, Article.validateThenCreate, private constructor, validation factory, identity generation, dependency injection, handler
3.7 Model identity: Filling the gap
Explains how entities can receive an identity while preserving, or explicitly qualifying, the Always-Valid Domain Model.
- In-scope identity creation: Explain why an entity needs an identity at construction and how an application-generated UUID meets that requirement. State that WriteFlow uses this approach rather than repository-generated IDs.
Why it matters: It shows how WriteFlow keeps identity creation compatible with its always-valid entities. - Repository-supplied identity: Explain the construction problem posed by infrastructure-generated IDs and how obtaining the next identity from a repository before construction addresses it.
Why it matters: It resolves the timing conflict between database-assigned identities and construction-time validity. - Transient identity trade-off: Describe the alternative of constructing an entity without an ID and assigning one after persistence, including its benefit and its cost.
Why it matters: It makes the cost of a simpler repository interface explicit rather than hiding a temporary gap in the model.
Key terms: in-scope identity, UUID, Always-Valid Domain Model, out-of-scope identity, repository, nextIdentity(), aggregate, transient "new" state, Architecture Decision Record, NewArticle
3.8 Two kinds of validation
This section distinguishes input validation from business invariant validation and assigns each validation responsibility to the appropriate layer of a hexagonal application.
- Input and business validation: Distinguish syntactic input validation from semantic business invariant validation by describing what each checks, where each belongs, and why invalid user input differs from a business rule violation.
Why it matters: The distinction tells you whether a check belongs at an input boundary or in the domain. - Validation ownership across layers: Trace validation in the article-creation request from REST adapter through command and domain entity, and explain why the handler and repository do not repeat checks owned by those layers.
Why it matters: Clear ownership prevents repeated checks while keeping malformed requests and invalid domain states from passing through.
Key terms: input validation, syntactic, business invariant validation, semantic, Always-Valid Domain Model, primary adapter, CreateArticleCommand, CreateArticleHandler, Article.validateThenCreate, secondary adapter
3.8.1 Input validation with the Validation monad
This section explains how commands use Validation to check input syntax at the boundary while the domain remains responsible for business rules.
- Command and domain validation boundaries: Distinguish input validation in commands from business validation in the domain, and describe the handler’s separate orchestration role.
Why it matters: Keeping these responsibilities separate prevents input checks from being mistaken for business rules. - Syntactically valid command construction: Explain how CreateArticleCommand.validate(...) controls command creation and what the primary adapter does with its result.
Why it matters: The handler can trust a command it receives without repeating syntax checks.
Key terms: Validation, commands, handlers, domain objects, syntax, business rules, CreateArticleCommand.validate(...), Validation monad, private constructor, validate factory method
3.9 Guard clauses
Guard clauses make validation easier to read by returning early for unmet preconditions, while the choice to stop at one failure or collect several depends on the operation.
- Guard Clause Purpose: Explain how guard clauses handle unmet preconditions and why they make validation logic easier to read.
Why it matters: Early checks let a reader see the normal path without working through layers of nesting. - Failure Handling Choice: Distinguish when an operation should stop at a failed precondition from when it may collect several validation errors.
Why it matters: The right response to invalid input depends on whether further checks can still give the caller useful information.
Key terms: guard clauses, precondition, happy path, fail fast, object creation, invalid states
3.10 Summary
Where this is used later
- (chapter intro) (chapter 4) · Assumes the domain layer has its own responsibilities.
- (chapter intro) (chapter 5) · Introduces the domain layer and its model.
- The Article aggregate: Creation, reconstitution, and behaviour (chapter 9) · Uses an Article aggregate with its own identity and constituent value objects.
- Commands and queries as typed input (chapter 4) · Develops commands and queries as typed inputs at the boundary.
- The mapping problem: A journey toward full isolation (chapter 5) · Examines mapping needed to keep models isolated across boundaries.
- What the domain guarantees (chapter 9) · The WriteFlow domain's guarantees depend on objects being valid whenever they exist.
- The validateThenCreate contract (chapter 7) · The structural rules check the validateThenCreate contract.
- Orchestration without business logic leakage (chapter 4) · Supports keeping business rules out of handler orchestration.
Concepts explained in this chapter
- factoryA construction abstraction that creates objects while encapsulating their creation logic.
- value objectA value object is an immutable domain object defined by its attributes rather than identity and responsible for enforcing the constraints of the concept it represents.
- always-valid domain modelA domain-modeling approach that prevents objects from representing states that violate their invariants.
- invariantA condition that must remain true for a domain object or business state to be valid.
- entityA domain object with an identity whose state and invariants are governed by domain rules.
- domain validationBusiness invariant validation checks whether domain data and operations satisfy the rules that must remain true for valid business state.
- syntax validationValidation that checks whether input has the required presence and format without evaluating its business meaning.
- domain serviceA domain service is a stateless domain-layer component that encapsulates business logic not naturally belonging to a single entity.
- validation resultValidation is a Vavr value type for applicatively accumulating validation errors or producing a valid value.
- domain layerA software layer that contains business concepts, rules, and behavior independently of infrastructure frameworks.
- EitherEither is a functional data type representing one of two alternatives, commonly a failure value or a successful result.
- validatethencreateA construction pattern that validates all required constraints before creating an object and returns validation errors instead of an invalid object.
- application serviceA service that coordinates an application use case and its domain operations without containing infrastructure concerns.
- application coreThe central part of an application containing its domain and application logic while remaining independent of external technologies.
- dependency injectionDependency injection is a design technique in which an object's dependencies are supplied by external configuration or infrastructure.
- data transfer objectA data transfer object is a data-carrying type designed to convey structured information between software components without encapsulating domain behavior.
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.
