Chapter 4: The honest hexagon: Use cases, commands, and the case against exceptions
Introduces the application layer’s coordinating role and explains why use case contracts should make failure explicit without changing what commands return on success.
After this chapter you will be able to
- Application layer responsibilities. Explain how the application layer sits between external actors and the domain, coordinating use cases while leaving business decisions to the domain model and communicating outward through output ports.
- Void command contract gap. Explain why a void command signature accurately says that no data is returned but does not tell callers how failure is represented.
- Explicit Either failure contract. Describe what each side of Either<Error, R> represents here and how commands and queries differ on the right-hand side.
- Application-layer use cases. Explain that meaningful WriteFlow actions, such as publishing an article or retrieving a feed, pass through the application layer as use cases.
- Input port boundary. Explain how input adapters call an input port and what the adapter is allowed to depend on.
- Use-case-owned interface contract. Describe how WriteFlow expresses an application capability as an input-port interface and how that differs from a framework-shaped service interface.
- Use Case Sequence. Describe how a use case accepts a self-validating command or query, enforces business rules through the domain model or ports, and signals an outcome to its caller.
- Validated Command Boundary. Explain why PublishArticleCommand must be validated before a use case receives it, and how validateThenCreate makes construction succeed completely or return all validation failures.
- Valid Input Versus Outcome. Distinguish a valid PublishArticleCommand from a successful publish use case, and explain what the current void handle signature leaves unsaid.
- Invisible use case failures. Explain why a void-returning use case signature is incomplete: it indicates that a valid command will do something but does not reveal what happens on failure. Distinguish that omission from the valid choice not to return data from a state-changing command.
- Contingencies Versus Faults. Distinguish expected application outcomes that callers can handle from unexpected faults for which exceptions remain appropriate.
- Visibility of Typed Outcomes. Explain what unchecked and checked exceptions reveal about recoverable failures, and why the section favors typed outcomes for expected failures.
- Exception Costs in Handlers. Explain why exceptions become especially costly when a hexagonal application handler coordinates collaborators that can fail in different ways.
- Explicit Use Case Outcomes. Distinguish what unchecked exceptions, checked exceptions, and a typed return value communicate about a use case’s expected failure paths.
- Honest use case contracts. Explain why a void signature for PublishArticleUseCase is an inadequate contract when the use case can fail, and why input adapters need failures made explicit.
- Honest command use case signature. Describe how the command use case's Either signature makes its failure path explicit: DomainError is on the left, while Void on the right means success returns no data. Explain why this changes what the use case promises its callers.
- Explicit command outcome contract. Explain why Either<DomainError, Void> is a different contract from void handle(...): callers can see and handle success and typed failure, rather than guess which undeclared exceptions might occur.
- Application error categories. Explain why application use cases need more than DomainError and describe the distinct outcomes the WriteFlow publish article flow may report.
- Expected technical contingencies. Distinguish a TechnicalError that can be translated into a use case outcome from an exceptional fault that may still propagate as an exception.
- Validation error abstraction levels. Distinguish ValidationErrors from ValidationError and explain why the singular field-level descriptor is outside the application Error hierarchy.
- Complete command validation errors. Explain that PublishArticleCommand uses the full Error type and that its factory method returns all validation failures at once, applying the validateThenCreate pattern to the complete error hierarchy.
- Command and query intents. Distinguish a command’s intent to change state from a query’s request for data, and describe both as immutable, self-validating, behavior-free typed inputs.
- Data and behavior separation. Explain how this book’s commands differ from Gang of Four Command objects and why execution behavior belongs in a handler.
- Application handler role. Describe the application handler as a class inside the hexagon that receives a command, coordinates the work, and returns the outcome.
- Handler implementation responsibilities. Explain how a handler implements a use case interface while depending on repositories and output ports rather than concrete infrastructure. Describe how it orchestrates the use case but leaves business decisions to the domain model.
- Either chain failure behavior. Trace what happens when a step in the handler’s chain succeeds or fails, and describe what the caller receives.
- Handler orchestration boundaries. Explain how a handler calls collaborators in the right order and lets an Either chain propagate failures, while leaving business conditions to the domain model, command validation to validateThenCreate, and persistence decisions to the repository.
- Framework-free handler boundaries. Explain why transaction boundaries, security checks, and logging attach to a handler as a whole, and why handlers express these concerns with technology-agnostic markers rather than framework annotations.
- Scaling adapter dependencies. Explain why directly injecting use case interfaces is adequate for one handler but becomes cumbersome as WriteFlow adds use cases.
- Command bus dispatch boundary. Describe how an adapter sends a command through the CommandBus, and distinguish that dispatch from HTTP routing.
- Input adapter coupling. Explain why replacing direct use-case injection with a CommandBus changes what input adapters depend on and lets new use cases be added without modifying existing adapters.
- Command handler registry. Trace how the bus finds a handler for a received command and describe what should happen when none is registered.
- Either-Based Command Contracts. Explain the roles of CommandHandler and CommandBus: handlers implement the former, while adapters depend on the latter as a single entry point for command execution. State that both interfaces use Either rather than exception-based variants.
- Use Case Bus Participation. Describe how PublishArticleUseCase participates in bus routing by extending CommandHandler, while its implementation remains unchanged. Explain that the handler can still be reached by direct injection as well as through the bus.
- Spring handler registration. Explain how SpringCommandBus finds available command handlers through Spring’s ApplicationContext, and what Spring does to make those handlers available.
- Command bus decorator chain. Explain how a decorator wraps the command bus to add behavior before or after command execution, and how multiple decorators form a chain.
- Command and query separation. Distinguish commands, which change state, from queries, which retrieve it. Explain that the query side follows the command side’s structural pattern but returns data, and that keeping the two separate helps handlers stay focused and the system predictable.
- Side-effect-free query contract. Explain that a query requests information without changing state, publishing events, or modifying infrastructure, and returns either an answer or an error explaining why it is unavailable.
- Separate read and write handlers. Distinguish the command handler’s write path from the query handler’s read path, and explain why they should not share a handler. State the section’s qualification that high-performance scenarios may also call for separate repository interfaces.
- Query Handler and Bus Contracts. Describe how QueryHandler and QueryBus relate to their command-side counterparts, including the result type parameter and the bus’s role as the single entry point for query execution.
- Article query path. Trace how the article-by-ID query reaches a handler through a use case and how the result returns to the caller without using the command path.
- Primary task and secondary reactions. Distinguish publishing an article from its consequences in WriteFlow, and explain why those consequences should not all be added to the publishing handler.
- Overloaded handler responsibilities. Explain why putting publishing and secondary tasks in one handler violates Single Responsibility and Open/Closed principles.
- Event Generation and Publication. Trace how the Article aggregate queues an ArticlePublished event when its status changes, and how the handler publishes queued events through an output port after saving the aggregate. Explain the limited ordering guarantee described here.
- Listener Based Secondary Reactions. Explain how separate input-adapter listeners react to a published event by invoking additional use cases, and why a new reaction need not change the publishing handler.
- Domain and integration events. Distinguish the chapter’s in-process domain event from an integration event intended for another bounded context or external system, and explain who owns any translation between them.
- Synchronous handling limits. Explain when a synchronous listener failure can roll back an operation, why external side effects may not be undone, and the broad trade-off of asynchronous handling.
What it builds on
- What lives inside the domain layer (chapter 3) · Assumes the domain layer has its own responsibilities.
- How a request travels through the hexagon (chapter 2) · The path a request takes through the hexagon.
- Core concepts: Ports and adapters (chapter 1) · The distinction between ports and adapters.
- The recommended approach: validateThenCreate (chapter 3) · The validateThenCreate approach to constructing always-valid objects.
- Input validation with the Validation monad (chapter 3) · The earlier treatment of input validation.
- The secret sauce: Dependency inversion (chapter 1) · Assumes the dependency-inversion boundary between the core and external technology.
Section by section
Introduction
Introduces the application layer’s coordinating role and explains why use case contracts should make failure explicit without changing what commands return on success.
- Application layer responsibilities: Explain how the application layer sits between external actors and the domain, coordinating use cases while leaving business decisions to the domain model and communicating outward through output ports.
Why it matters: This distinction keeps application coordination from absorbing domain rules. - Void command contract gap: Explain why a void command signature accurately says that no data is returned but does not tell callers how failure is represented.
Why it matters: A caller needs to see the possible failure path as well as the success return. - Explicit Either failure contract: Describe what each side of Either<Error, R> represents here and how commands and queries differ on the right-hand side.
Why it matters: The signature can expose failure without making a command return success data.
Key terms: application layer, domain model, output ports, void, use case contract, exception, Either<Error, R>, typed error, Command-Query Separation (CQS)
4.1 The use case contract
Introduces use cases as the application-layer path for WriteFlow actions and explains how @UseCase marks an input-port interface.
- Application-layer use cases: Explain that meaningful WriteFlow actions, such as publishing an article or retrieving a feed, pass through the application layer as use cases.
Why it matters: It identifies where user actions enter the application before looking at individual use-case contracts. - UseCase annotation as marker: Describe @UseCase as an Architecture Kernel stereotype that identifies an interface as an input port without adding runtime behavior.
Why it matters: The marker makes an interface's intended architectural role visible without making the annotation responsible for runtime work.
Key terms: use case, application layer, @UseCase, Architecture Kernel, stereotype annotation, input port
4.1.1 Input ports: The hexagon's public API
This section defines input ports as use-case-owned interfaces through which technology-specific adapters drive WriteFlow without depending on handler implementations.
- Input port boundary: Explain how input adapters call an input port and what the adapter is allowed to depend on.
Why it matters: That boundary lets different delivery mechanisms call the same application capability without coupling themselves to its implementation. - Use-case-owned interface contract: Describe how WriteFlow expresses an application capability as an input-port interface and how that differs from a framework-shaped service interface.
Why it matters: A use-case-owned contract makes the application's capability clear before adapters and frameworks shape how it is delivered. - Architecture Kernel purpose: Distinguish WriteFlow’s Architecture Kernel from a DDD Shared Kernel.
Why it matters: The distinction explains how modules can share architectural contracts without putting business concepts into that shared module.
Key terms: input port, input adapter, handler, hexagon boundary, use case, PublishArticleUseCase, PublishArticleCommand, handle, Architecture Kernel, DDD Shared Kernel
4.1.2 The anatomy of a use case
This section explains the sequence of a use case, why it receives validated commands, and why valid input does not guarantee a successful outcome.
- Use Case Sequence: Describe how a use case accepts a self-validating command or query, enforces business rules through the domain model or ports, and signals an outcome to its caller.
Why it matters: This sequence gives you a way to describe a use case without tying it to a particular task. - Validated Command Boundary: Explain why PublishArticleCommand must be validated before a use case receives it, and how validateThenCreate makes construction succeed completely or return all validation failures.
Why it matters: Rejecting invalid input before the handler keeps input checks separate from the decision to publish. - Valid Input Versus Outcome: Distinguish a valid PublishArticleCommand from a successful publish use case, and explain what the current void handle signature leaves unsaid.
Why it matters: A trustworthy command does not by itself tell the caller whether publishing succeeded.
Key terms: use case, command, query, domain model, output ports, outcome, PublishArticleCommand, validateThenCreate, handler, application layer
4.2 The incomplete contract
This section shows why a use case signature can correctly return no command data yet still leave its failure contract incomplete.
- Invisible use case failures: Explain why a void-returning use case signature is incomplete: it indicates that a valid command will do something but does not reveal what happens on failure. Distinguish that omission from the valid choice not to return data from a state-changing command.
Why it matters: It helps you spot a missing failure contract without mistaking every void command for a design error.
Key terms: use case, command, void, failure path, exception
4.2.1 The cost of using exceptions for expected failures
The section argues that expected use case failures should be explicit outcomes rather than exceptions, while reserving exceptions for faults that require diagnosis.
- Contingencies Versus Faults: Distinguish expected application outcomes that callers can handle from unexpected faults for which exceptions remain appropriate.
Why it matters: The distinction helps callers handle ordinary failures without treating them as system faults. - Visibility of Typed Outcomes: Explain what unchecked and checked exceptions reveal about recoverable failures, and why the section favors typed outcomes for expected failures.
Why it matters: An explicit result tells callers what ordinary failures to handle without requiring a separate exception path. - Costs of Exception Control Flow: Describe how throwing exceptions for expected failures affects execution flow, failure tests, and reporting multiple invalid fields.
Why it matters: These costs make ordinary failures harder to follow, verify, and report to callers.
Key terms: contingencies, faults, use case contract, unchecked exceptions, checked exceptions, typed outcomes, Either, call stack, control flow, assertThrows
4.2.2 The hidden cost in a hexagonal architecture
This section explains why exception-based failures complicate use-case handlers and why typed return values make their possible outcomes explicit.
- Exception Costs in Handlers: Explain why exceptions become especially costly when a hexagonal application handler coordinates collaborators that can fail in different ways.
Why it matters: It explains why handling failures is part of keeping a use-case handler clear. - Explicit Use Case Outcomes: Distinguish what unchecked exceptions, checked exceptions, and a typed return value communicate about a use case’s expected failure paths.
Why it matters: A use-case contract is easier to understand when it makes expected outcomes visible together.
Key terms: application layer, handler, repositories, output ports, domain services, try-catch blocks, unchecked exceptions, checked exceptions, method signature, typed return value
4.2.3 A deliberately provocative question
This section argues that use-case signatures should tell input adapters what can go wrong, just as public API contracts do.
- Honest use case contracts: Explain why a void signature for PublishArticleUseCase is an inadequate contract when the use case can fail, and why input adapters need failures made explicit.
Why it matters: Treating input adapters as API consumers makes the need for an explicit failure contract clear.
Key terms: application layer, input adapters, use cases, void handle(PublishArticleCommand command)
4.3 Either: An honest signature
Introduces Either as an explicit return value for use cases, making success and failure visible in the use case signature.
- Either success and failure branches: Explain that Either holds one of two return values: a left value for failure or a right value for success. Distinguish it from an exception, which unwinds the call stack.
Why it matters: This explains why a caller can see the failure path instead of discovering it through an exception. - Honest command use case signature: Describe how the command use case's Either signature makes its failure path explicit: DomainError is on the left, while Void on the right means success returns no data. Explain why this changes what the use case promises its callers.
Why it matters: The signature tells callers that failure is part of the use case contract, not a hidden possibility.
Key terms: Either<L, R>, left, right, Vavr's Either, Either, DomainError, Void, command, use case contract
4.3.1 What Either says that the void did not
This section shows how an Either return type makes a command’s success and failure outcomes explicit without turning the command into a query.
- Explicit command outcome contract: Explain why Either<DomainError, Void> is a different contract from void handle(...): callers can see and handle success and typed failure, rather than guess which undeclared exceptions might occur.
Why it matters: An explicit outcome contract lets callers account for failure without discovering it by surprise. - Command outcome versus query data: Explain why returning Either<DomainError, Void> from a command preserves Command-Query Separation: it reports success or typed failure, not business data.
Why it matters: Reporting whether a command succeeded does not make it a data-returning query.
Key terms: void handle(...), Either<DomainError, Void>, two-branch return value, CQS, Command-Query Separation, outcome signal
4.3.2 The Error hierarchy
This section defines an application-level error taxonomy that distinguishes use case failures while keeping field-level validation details and unexpected exceptions in their proper places.
- Application error categories: Explain why application use cases need more than DomainError and describe the distinct outcomes the WriteFlow publish article flow may report.
Why it matters: Distinct errors let callers respond appropriately rather than treating every failure alike. - Expected technical contingencies: Distinguish a TechnicalError that can be translated into a use case outcome from an exceptional fault that may still propagate as an exception.
Why it matters: This boundary avoids hiding genuine defects while making anticipated infrastructure failures explicit. - Closed error type family: Describe what sealing the Error hierarchy tells the compiler about possible application errors.
Why it matters: A closed error family makes the use case’s possible error types explicit. - Validation error abstraction levels: Distinguish ValidationErrors from ValidationError and explain why the singular field-level descriptor is outside the application Error hierarchy.
Why it matters: The separation lets a use case report invalid input without confusing one field problem with the whole failure.
Key terms: DomainError, Error, input adapters, TechnicalError, exceptions, application boundary, sealed hierarchy, root interface, ValidationErrors, ValidationError
4.3.3 Returning multiple validation failures at once
This subsection updates PublishArticleCommand validation to return all failures using the full Error hierarchy.
- Complete command validation errors: Explain that PublishArticleCommand uses the full Error type and that its factory method returns all validation failures at once, applying the validateThenCreate pattern to the complete error hierarchy.
Why it matters: Callers can receive the command's validation failures together through the established error contract.
Key terms: PublishArticleCommand, Error, validateThenCreate, validation failures
4.3.4 Commands and queries as typed input
This section defines commands and queries as typed, data-only inputs and explains why their behavior lives in handlers instead of the inputs themselves.
- Command and query intents: Distinguish a command’s intent to change state from a query’s request for data, and describe both as immutable, self-validating, behavior-free typed inputs.
Why it matters: This distinction makes the purpose of each input clear before a handler processes it. - Data and behavior separation: Explain how this book’s commands differ from Gang of Four Command objects and why execution behavior belongs in a handler.
Why it matters: Keeping execution out of commands preserves their role as testable data carriers. - Command and query markers: Explain what the Architecture Kernel’s command and query marker interfaces do despite having no methods.
Why it matters: The markers give routing and architecture checks a way to tell the two input kinds apart.
Key terms: command, query, typed input, GoF Command, handler, bus, marker interface, Architecture Kernel, ArchUnit
4.4 The Application handler
This section introduces the application handler as the class inside the hexagon that receives a command, coordinates work, and returns an outcome.
- Application handler role: Describe the application handler as a class inside the hexagon that receives a command, coordinates the work, and returns the outcome.
Why it matters: This gives you the handler’s role before its implementation is described.
Key terms: Application handler, PublishArticleCommand, Either<Error, Void>
4.4.1 From use case interface to handler implementation
This section explains how a handler turns a use case interface into application work and returns a typed outcome through an Either chain.
- Handler implementation responsibilities: Explain how a handler implements a use case interface while depending on repositories and output ports rather than concrete infrastructure. Describe how it orchestrates the use case but leaves business decisions to the domain model.
Why it matters: This separation lets the application do useful work without tying its use case to infrastructure or moving business decisions out of the domain. - Either chain failure behavior: Trace what happens when a step in the handler’s chain succeeds or fails, and describe what the caller receives.
Why it matters: The caller can see success or a typed failure in the handler’s returned value.
Key terms: handler, use case interface, repositories, output ports, domain model, Either, typed error, short-circuits, try-catch
4.4.2 Orchestration without business logic leakage
This section explains how a handler orchestrates a use case without taking over validation, business rules, or persistence decisions.
- Handler orchestration boundaries: Explain how a handler calls collaborators in the right order and lets an Either chain propagate failures, while leaving business conditions to the domain model, command validation to validateThenCreate, and persistence decisions to the repository.
Why it matters: This distinction helps keep use-case handlers thin without moving domain rules out of the domain.
Key terms: handler, orchestration, domain invariant, Article.publish(), validateThenCreate, repository
4.4.3 Cross-cutting concerns at the boundary
This section places cross-cutting concerns at the handler boundary without introducing framework dependencies, and keeps domain objects out of command results.
- Framework-free handler boundaries: Explain why transaction boundaries, security checks, and logging attach to a handler as a whole, and why handlers express these concerns with technology-agnostic markers rather than framework annotations.
Why it matters: A framework annotation in a handler weakens the architectural boundary and makes handler tests depend on that framework. - Command result encapsulation: Explain why a command handler returns Either<Error, Void> rather than a domain entity, and what a caller should use if it needs data after the command.
Why it matters: Separating command results from queries keeps adapters from depending on the domain model's internal structure.
Key terms: handler, cross-cutting concerns, application core, Architecture Kernel, technology-agnostic annotations, adapter, Either<Error, Void>, domain objects, use case interface, query
4.5 The command bus
This section explains why WriteFlow introduces a command bus and how it dispatches application commands without making adapters depend on individual handlers.
- Scaling adapter dependencies: Explain why directly injecting use case interfaces is adequate for one handler but becomes cumbersome as WriteFlow adds use cases.
Why it matters: It explains the problem the command bus is meant to solve, rather than treating the bus as mandatory for every application. - Command bus dispatch boundary: Describe how an adapter sends a command through the CommandBus, and distinguish that dispatch from HTTP routing.
Why it matters: It shows how the adapter can invoke a use case without knowing which handler implements it.
Key terms: use case interface, handler, adapter, injection graph, CommandBus, command, registry, command handler, HTTP router
4.5.1 Why a bus? From one handler to many
This subsection explains how a command bus reduces input-adapter coupling by routing commands to registered handlers.
- Input adapter coupling: Explain why replacing direct use-case injection with a CommandBus changes what input adapters depend on and lets new use cases be added without modifying existing adapters.
Why it matters: The benefit of the bus is reduced adapter coupling, not simply a different way to call a handler. - Command handler registry: Trace how the bus finds a handler for a received command and describe what should happen when none is registered.
Why it matters: The registry makes command routing possible without putting routing decisions in input adapters.
Key terms: direct injection, input adapter, CommandBus, Open/Closed principle, registry, command type, handler, fail fast
4.5.2 The Command Bus in the Architecture Kernel
Defines the Architecture Kernel’s Either-based command bus contract and shows how a use case joins bus routing without changing its handler implementation.
- Either-Based Command Contracts: Explain the roles of CommandHandler and CommandBus: handlers implement the former, while adapters depend on the latter as a single entry point for command execution. State that both interfaces use Either rather than exception-based variants.
Why it matters: These contracts let adapters invoke commands through one bus-facing interface while handlers retain an explicit result type. - Use Case Bus Participation: Describe how PublishArticleUseCase participates in bus routing by extending CommandHandler, while its implementation remains unchanged. Explain that the handler can still be reached by direct injection as well as through the bus.
Why it matters: A use case can gain bus routing without rewriting its handler or giving up direct injection.
Key terms: Architecture Kernel, CommandHandler, CommandBus, Either, PublishArticleUseCase, Either<Error, Void>, direct injection, bus routing
4.5.3 Spring wiring: Handlers as beans
This subsection explains how Spring-managed handlers become available to the command bus and how a REST controller uses the bus instead of injecting a use case directly.
- Spring handler registration: Explain how SpringCommandBus finds available command handlers through Spring’s ApplicationContext, and what Spring does to make those handlers available.
Why it matters: It explains where the bus gets its handlers without manual registration. - Controller bus dependency: Describe the change to the REST controller’s injected dependency when the command bus is in place.
Why it matters: It identifies the input adapter’s point of contact with the bus.
Key terms: SpringCommandBus, ApplicationContext, CommandHandler bean, handler registry, REST controller, PublishArticleUseCase, CommandBus, input adapter
4.5.4 Decorating the bus: Logging and metrics
This section shows how command bus decorators add cross-cutting behavior around every command without changing handlers, and distinguishes that role from domain events.
- Command bus decorator chain: Explain how a decorator wraps the command bus to add behavior before or after command execution, and how multiple decorators form a chain.
Why it matters: You can add logging or metrics to every command without putting that code in each handler. - Decorators versus domain events: Distinguish technical behavior added around use case execution by decorators from domain-specific consequences of a state change represented by domain events.
Why it matters: The distinction helps you place technical instrumentation and business reactions in the appropriate mechanism.
Key terms: CommandBus, Decorator pattern, LoggingCommandBus, decorator chain, dependency injection, decorators, domain events, cross-cutting concerns
4.6 The query bus
This section distinguishes queries from commands and introduces the query side of the bus as a similar structure whose handler returns data.
- Command and query separation: Distinguish commands, which change state, from queries, which retrieve it. Explain that the query side follows the command side’s structural pattern but returns data, and that keeping the two separate helps handlers stay focused and the system predictable.
Why it matters: The distinction clarifies what each handler is meant to do and what a caller can expect back.
Key terms: commands, queries, handler, query side
4.6.1 Queries are not commands
This section distinguishes side-effect-free queries from commands and shows how that distinction separates read and write handlers.
- Side-effect-free query contract: Explain that a query requests information without changing state, publishing events, or modifying infrastructure, and returns either an answer or an error explaining why it is unavailable.
Why it matters: The read-only contract makes clear what callers can expect from a query. - Separate read and write handlers: Distinguish the command handler’s write path from the query handler’s read path, and explain why they should not share a handler. State the section’s qualification that high-performance scenarios may also call for separate repository interfaces.
Why it matters: Keeping the paths distinct prevents a read request from being treated like a state-changing operation.
Key terms: query, side effects, command handler, query handler, write path, read path, DTO, repository interface
4.6.2 QueryHandler and QueryBus
Introduces the Architecture Kernel’s query-side handler and bus as counterparts to the command-side interfaces.
- Query Handler and Bus Contracts: Describe how QueryHandler and QueryBus relate to their command-side counterparts, including the result type parameter and the bus’s role as the single entry point for query execution.
Why it matters: This identifies the query-side contracts without assuming that queries return the same kind of result.
Key terms: QueryHandler, QueryBus, result type parameter, Architecture Kernel
4.6.3 CQS in practice
Shows how WriteFlow retrieves an article through a separate query path and returns a read-side DTO rather than a domain entity.
- Article query path: Trace how the article-by-ID query reaches a handler through a use case and how the result returns to the caller without using the command path.
Why it matters: It shows how a read request stays separate from the path that changes article state. - Read-side DTO projection: Distinguish the DTO returned by the article query from the domain entity that enforces business rules, and describe the query's construction pattern.
Why it matters: It clarifies why a read result is shaped for the caller rather than exposing the business-rule-enforcing aggregate.
Key terms: query, QueryHandler, query bus, use case interface, handler, DTO, Data Transfer Object, projection, aggregate, validateThenCreate
4.7 Domain events: A first look
The section distinguishes publishing an article from the work that follows it and explains why the publishing handler should not own every consequence.
- Primary task and secondary reactions: Distinguish publishing an article from its consequences in WriteFlow, and explain why those consequences should not all be added to the publishing handler.
Why it matters: Keeping the publishing handler focused makes it possible to add follow-up work without continually expanding that handler.
Key terms: primary use case, secondary reactions, handler, state change
4.7.1 When the primary task is done, then what?
This section explains why putting secondary tasks in a handler makes it fragile and difficult to extend.
- Overloaded handler responsibilities: Explain why putting publishing and secondary tasks in one handler violates Single Responsibility and Open/Closed principles.
Why it matters: This explains why a handler that works today can become fragile as secondary tasks accumulate.
Key terms: handler, Single Responsibility, Open/Closed, secondary task
4.7.2 Generating events in the domain, publishing in the application layer
This section shows how WriteFlow records a publishing event in the domain, publishes it after saving, and handles secondary reactions in separate listeners.
- Domain Event Meaning: Describe a domain event as an immutable, past-tense record of a significant domain occurrence that carries data rather than behaviour.
Why it matters: This distinction keeps the fact of publication separate from what other parts of the application do about it. - Event Generation and Publication: Trace how the Article aggregate queues an ArticlePublished event when its status changes, and how the handler publishes queued events through an output port after saving the aggregate. Explain the limited ordering guarantee described here.
Why it matters: Keeping event generation in the domain and publication timing in the handler preserves their distinct responsibilities. - Listener Based Secondary Reactions: Explain how separate input-adapter listeners react to a published event by invoking additional use cases, and why a new reaction need not change the publishing handler.
Why it matters: Separate listeners let the application gain new reactions without accumulating them in the primary handler.
Key terms: domain event, ArticlePublished, Article aggregate, application handler, output port, queued events, input adapters, listeners, secondary reaction, Open/Close principle
4.7.3 Forward: The full event story
This section distinguishes local domain events from external integration events and explains the limits of synchronous event handling.
- Event responsibility boundaries: Trace the event pattern from domain generation through handler publication to listener reaction.
Why it matters: This separation keeps event handling aligned with the hexagon’s boundaries. - Domain and integration events: Distinguish the chapter’s in-process domain event from an integration event intended for another bounded context or external system, and explain who owns any translation between them.
Why it matters: It prevents an internal domain event from being mistaken for a message that must be sent to other systems. - Synchronous handling limits: Explain when a synchronous listener failure can roll back an operation, why external side effects may not be undone, and the broad trade-off of asynchronous handling.
Why it matters: A listener running synchronously does not make all its side effects reversible.
Key terms: domain, handler, listener, bounded context, ArticlePublished, domain event, integration event, application layer, synchronous, asynchronous handling
4.8 Summary
Where this is used later
- Error mapping: from Error hierarchy to HTTP responses (chapter 5) · Maps errors from the explicit error contract to HTTP responses.
- Annotation rules: The right stereotype in the right place (chapter 7) · Examines rules about architectural stereotype annotations.
- What an input adapter is (and is not) (chapter 5) · Distinguishes an input adapter from the port it calls.
- Structural rules: Shape enforcement (chapter 7) · Introduces input ports as interfaces.
- Input ports: The use cases the application offers (chapter 9) · Defines the input ports offered by the completed WriteFlow application.
- Testing the validation path (chapter 8) · Tests exercise the validation path for command creation.
- Transactionality: Boundaries the framework resolves (chapter 6) · Introduces Either as an explicit way to represent failure.
- The Either problem: No exception, no rollback? (chapter 6) · Either expresses failure as a returned value.
Concepts explained in this chapter
- command and query busAn application component that accepts commands through a uniform interface and dispatches them to corresponding handlers.
- EitherEither is a functional data type representing one of two alternatives, commonly a failure value or a successful result.
- domain eventAn immutable representation of a significant occurrence expressed in the language of the business domain.
- commandA command object encapsulates data representing a requested application operation.
- handlerA handler is an application component that processes a request and coordinates the interactions needed to fulfill it.
- primary portAn interface exposing an application operation that an external caller can invoke.
- use caseA use case is an application operation that coordinates domain rules to accomplish a specific user or system goal.
- queryA query is a request that retrieves information without changing application or domain state.
- architecture kernelThe Architecture Kernel is a book-specific framework-independent component that provides technology-agnostic annotations for expressing architectural intent.
- exceptionAn exception is a Java control-flow mechanism that represents an abnormal condition by transferring execution to exception-handling code.
- command-query separationA software design principle that separates operations that change state from operations that return information without changing state.
- query busA query bus dispatches query requests to their corresponding handlers through a single entry point.
- error typeAn error represented by a distinct type so that its category and handling behavior are explicit.
- application layerA software layer that coordinates application operations and use cases above the domain layer.
- handler registryA mapping from operation types or other keys to the handlers responsible for processing them.
- event handlerA component that reacts to a published event by invoking additional behavior.
- command handlerA command handler processes a command representing an application state change.
- outbound portAn application-facing boundary that declares a service the application requires from an external system.
- driving adapterA primary adapter translates an external trigger into a call to an application input port.
- domain modelA software representation of the concepts, relationships, and rules of a business domain.
- factoryA construction abstraction that creates objects while encapsulating their creation logic.
- integration eventA published event contract representing an occurrence in a stable form suitable for consumers across system boundaries.
- adapterAn adapter that connects an application to an external service through an API.
- application coreThe central part of an application containing its domain and application logic while remaining independent of external technologies.
- system boundaryA structural separation that defines permitted responsibilities and dependencies between parts of a software system.
- data transfer objectA data transfer object is a data-carrying type designed to convey structured information between software components without encapsulating domain behavior.
- projectionA projection is a read-only view containing selected data from a domain model rather than the domain entity itself.
- invariantA condition that must remain true for a domain object or business state to be valid.
- orchestrationThe coordination of collaborators to complete an application operation without owning the underlying business rules.
- validatethencreateA construction pattern that validates all required constraints before creating an object and returns validation errors instead of an invalid object.
- transaction boundaryA transaction boundary defines the scope within which a set of operations participates in one atomic transaction.
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.
