Overview

3 Building the domain core

This chapter focuses on building the business core of a hexagonal application so that correctness is enforced where it matters most. The central idea is to rebuild domain concepts first, away from infrastructure and frameworks, so the model is small, testable, and free from accidental complexity. Rather than starting with databases, controllers, or APIs, the chapter argues for starting with the business rules and invariants that must always hold, then shaping the code so invalid states cannot exist.

It explains how to decide what belongs in the domain layer and how to structure that layer around entities, value objects, aggregates, and domain services. Entities represent business concepts with identity, value objects represent meaningful concepts without identity, and domain services capture business logic that spans multiple concepts. The chapter also emphasizes three design principles—purity, encapsulation, and completeness—so domain code depends only on its inputs, hides its internal state, and gives every input a defined outcome. This makes the model predictable, easier to reason about, and very fast to test.

A major theme is the Always-Valid Domain Model: domain objects should only be created through factory methods that validate all invariants before construction. The chapter contrasts this with weaker approaches such as validating after construction or moving business rules into handlers, and shows why those approaches leak responsibility and allow invalid objects to exist. It then extends the idea to value objects, factories, identity generation, and domain services, while separating business invariant validation from input validation at the edges of the system. The result is a domain core that is explicit, framework-independent, and designed for reliable evolution.

The contrast between domain and infrastructure concerns.
The contrast between domain and infrastructure concerns.
The domain layer inside the hexagon. Shows entities, value objects, aggregates, and domain services inside the innermost ring. Ports sit at the ring boundary. Adapters and frameworks are outside. Arrows emphasize that nothing from outside points inward into the domain.
The domain layer inside the hexagon. Shows entities, value objects, aggregates, and domain services inside the innermost ring. Ports sit at the ring boundary. Adapters and frameworks are outside. Arrows emphasize that nothing from outside points inward into the domain.
Persistence and serialization frameworks may require construction paths that do not express domain rules clearly. The domain model keeps creation explicit: callers enter through validateThenCreate, and the private constructor is reached only after invariants pass
Persistence and serialization frameworks may require construction paths that do not express domain rules clearly. The domain model keeps creation explicit: callers enter through validateThenCreate, and the private constructor is reached only after invariants pass
Primitive obsession vs value objects. Left: method signature with String, String, Long parameters—no type safety, validation scattered. Right: same method with Title, Content, AuthorId parameters—each type self-validating, compiler enforces correctness.
Primitive obsession vs value objects. Left: method signature with String, String, Long parameters—no type safety, validation scattered. Right: same method with Title, Content, AuthorId parameters—each type self-validating, compiler enforces correctness.
Validation checkpoints across layers. Shows the flow from HTTP request through adapter → command → handler → domain entity → repository. Green checkmarks at adapter (transport validation), command (input validation), and domain entity (business invariants). Gray pass-through at the handler and repository—they trust upstream validation.
Validation checkpoints across layers. Shows the flow from HTTP request through adapter → command → handler → domain entity → repository. Green checkmarks at adapter (transport validation), command (input validation), and domain entity (business invariants). Gray pass-through at the handler and repository—they trust upstream validation.

Summary

  • The domain layer is the innermost ring of the hexagon. It contains entities, value objects, aggregates, and domain services—all pure code with no framework dependencies.
  • Three functional principles—purity, encapsulation, and completeness—guide domain design. Maximize them where they matter most: in entities and value objects.
  • The Always-Valid Domain Model is the single most important design decision in the domain layer. The constructor is private; the only way to create a domain object is through a factory method that validates all invariants first. If validation fails, the factory returns an error, not an invalid object.
  • The recommended pattern is validateThenCreate using Vavr's Validation type, which can run several checks and return all validation errors together instead of stopping at the first one. The CanBeCreated pattern is a defensible alternative when CQS adherence is a priority.
  • Value objects replace simple language types with domain concepts. A Title type that enforces its own constraints is safer and more expressive than a raw String.
  • Domain services handle business logic that spans multiple entities. They live in the domain layer, carry no framework annotations, and are pure functions of their inputs.
  • Factories encapsulate object construction. For simple entities, the factory method lives on the entity class. For complex construction involving identity generation or external lookups, use a standalone factory class.
  • Input validation (syntactic) guards the hexagon's boundaries. Business invariant validation (semantic) guards the domain itself. They use different mechanisms and live in different layers.

FAQ

What belongs inside the domain layer in hexagonal architecture?The domain layer should contain only business concepts that represent rules or invariants the system must always obey. This includes entities, value objects, aggregates, and domain services. Framework annotations, persistence concerns, REST controllers, messaging, and security infrastructure belong outside the domain.
What is the Always-Valid Domain Model?The Always-Valid Domain Model is the idea that invalid domain objects should never be instantiated. A domain object is created only after all business invariants are validated, so if the object exists, it is already valid.
Why should entity constructors be private?Private constructors prevent callers from creating incomplete or invalid entities directly. They force object creation through a factory method, which can validate all invariants before constructing the entity.
What is the recommended way to create a valid domain entity?The recommended approach is a validateThenCreate factory method. It validates all required fields, returns a valid entity when checks pass, and returns one or more domain errors when validation fails.
Why is validation after construction a bad idea?Because it allows an invalid object to exist in memory, even if only briefly. That breaks the Always-Valid Domain Model and can lead to bugs, especially in concurrent systems where other code might access the object before validation runs.
What is the difference between input validation and business invariant validation?Input validation checks the shape of data at the system boundary, such as blank fields or malformed UUIDs. Business invariant validation checks domain rules, such as whether an article can exist without content or whether a publication period has a valid start and end date.
What is a value object, and why use one?A value object represents a domain concept without identity. It is immutable and defined by its attributes. Value objects make implicit concepts explicit, reduce primitive obsession, and enforce constraints at construction time.
When should you use a domain service?Use a domain service when business logic spans multiple entities or aggregates and does not naturally belong to just one entity. A domain service contains business rules, not orchestration logic, and usually has no infrastructure dependencies.
When should you use a standalone factory instead of an entity factory method?Use a standalone factory when object creation requires external services, such as generating an ID or looking up related data. If the entity can be created using only its own fields, keep the factory method on the entity itself.
Why are value objects often good candidates for Java records, while entities are not?Records work well for value objects because they are immutable and typically validated in their canonical constructor. Entities often need a private constructor and a controlled creation path, which records do not support in a way that fits the Always-Valid Domain Model.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Clean Applications with Hexagonal Architecture Clean Applications with Hexagonal Architecture ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Clean Applications with Hexagonal Architecture Clean Applications with Hexagonal Architecture ebook for free