Overview

4 The honest hexagon: Use cases, commands, and the case against exceptions

This chapter draws the boundary between the domain and the application layer, showing how use cases become the hexagon’s public API. A use case is expressed as an input port with a domain-focused contract, and its inputs are self-validating commands or queries rather than raw request data. That means validation happens before the application layer sees the object, so handlers can focus on business orchestration instead of checking for nulls or malformed fields.

The core argument is that returning void leaves a use case contract incomplete, because success is visible but failure is not. Expected failures such as missing entities, permission problems, or validation issues should not be hidden behind exceptions, since exceptions obscure control flow, weaken compiler guidance, and make testing awkward. Instead, the chapter replaces exception-centered design with Either<Error, R>, pairing success with an explicit, typed failure path that callers must acknowledge and handle.

From there, the chapter builds the application layer around typed commands and queries, dedicated handlers, and routing buses. Commands change state and return Either<Error, Void>, while queries retrieve data and return Either<Error, R>; both stay focused by preserving Command-Query Separation. The chapter also introduces a sealed error hierarchy, then shows how a command bus and query bus reduce coupling as the application grows. Finally, it offers a first look at domain events as the clean way to trigger side effects after the main use case completes, keeping the primary handler small and the system open for extension.

An input port at the hexagon boundary. The REST controller depends on the interface, never on the concrete handler. Dependency flows inward; the handler is invisible to the outside world.
An input port at the hexagon boundary. The REST controller depends on the interface, never on the concrete handler. Dependency flows inward; the handler is invisible to the outside world.
The sealed Error hierarchy for WriteFlow. BusinessError and TechnicalError are nested sealed interfaces with their own record subtypes. ValidationErrors carries a list of ValidationError instances, which live in a separate sealed hierarchy outside Error. MultipleErrors allows composing multiple errors from different categories into a single failure.
The sealed Error hierarchy for WriteFlow. BusinessError and TechnicalError are nested sealed interfaces with their own record subtypes. ValidationErrors carries a list of ValidationError instances, which live in a separate sealed hierarchy outside Error. MultipleErrors allows composing multiple errors from different categories into a single failure.
Command bus routing. The controller sends a command to the bus. The bus looks up the handler through a registry and delegates execution. The controller never knows which handler processed the command.
Command bus routing. The controller sends a command to the bus. The bus looks up the handler through a registry and delegates execution. The controller never knows which handler processed the command.
Decorator chain. The adapter calls a single CommandBus interface. Behind it, decorators wrap the real bus, each adding one concern. The handler at the end is resolved through the registry and is invisible to the adapter. Adding or removing decorators requires no changes to handlers or adapters.
Decorator chain. The adapter calls a single CommandBus interface. Behind it, decorators wrap the real bus, each adding one concern. The handler at the end is resolved through the registry and is invisible to the adapter. Adding or removing decorators requires no changes to handlers or adapters.
The domain event flow. The aggregate generates the event. The handler publishes it after the save. An input adapter listens and invokes a new use case. The event exits the hexagon through an output port and re-enters through an input adapter—maintaining the architectural boundary in both directions.
The domain event flow. The aggregate generates the event. The handler publishes it after the save. An input adapter listens and invokes a new use case. The event exits the hexagon through an output port and re-enters through an input adapter—maintaining the architectural boundary in both directions.

Summary

  • Input ports are interfaces that define what the application can do, expressed in domain language. They are the hexagon's public API—the only surface adapters depend on.
  • The void return type on a command is correct in intent—commands do not return data. But combined with exceptions as the sole error channel, it leaves the failure path invisible to the compiler, to callers, and to tests.
  • Either<Error, Void> completes the contract without violating CQS. The right side remains Void—no data returned. The left side carries a typed error. Both outcomes are explicit, and both are compiler-enforced.
  • The Error sealed hierarchy distinguishes between BusinessError (domain rule violations), TechnicalError (infrastructure failures), and ValidationErrors (malformed input carrying a list of ValidationError instances). Each category maps to distinct adapter responses.
  • Commands and queries are typed, self-validating input data carriers. They implement marker interfaces (Command, Query) from the Architecture Kernel and use the validateThenCreate factory method to guarantee validity at construction—never throwing, always returning Either.
  • Application handlers orchestrate without owning business logic. They coordinate repositories and output ports, delegate business decisions to the domain model, and return Either. Cross-cutting concerns may attach through technology-agnostic annotations from the Architecture Kernel.
  • The command bus and query bus decouple adapters from handlers. The adapter injects one interface—CommandBus or QueryBus—and the bus resolves the correct handler at runtime through a registry. Adding a new use case means adding a new handler class—no adapter changes, no wiring updates.
  • In WriteFlow, the application skeleton now has one write slice and one read slice: publishing an article through PublishArticleCommand and retrieving an article through GetArticleByIdQuery. Both enter through validated input objects, flow through a bus, reach a handler, and return explicit Either-based outcomes.
  • Decorators wrap the bus to add technical cross-cutting behavior—logging, metrics, tracing, validation, or security propagation—without modifying handlers or adapters. They compose into chains controlled at assembly time and are different from domain events, which model domain-specific consequences of state changes.
  • Domain events separate primary tasks from secondary reactions. The aggregate generates the event, the handler publishes it after persistence, and input adapters listen and invoke additional use cases. Each secondary reaction lives in its own class, independently addable and removable.

FAQ

What is a use case in hexagonal architecture?A use case is an application-layer capability exposed through an input port. It represents a meaningful action the system can perform, such as publishing an article or retrieving a feed, and it coordinates domain objects without owning business logic.
Why does the chapter call the application layer “the honest hexagon”?Because the application layer should make its contract explicit. It should clearly state what input it accepts, what it can return, and how it can fail, rather than hiding failure behind exceptions or framework conventions.
What is an input port?An input port is the public API of the hexagon. It is typically a Java interface that defines what the application can do in domain language, independent of HTTP, messaging, scheduling, or any other delivery mechanism.
Why is a command object validated before it reaches the handler?To ensure the handler receives only valid, trusted input. Validation happens at the boundary, so the handler can focus on business questions like “Can this article be published?” instead of checking for nulls or malformed data.
What problem does Either<Error, R> solve compared to void return types?void tells you nothing about failure. Either<Error, R> makes failure part of the method contract, so the compiler and caller both see success and failure paths explicitly.
Why are exceptions discouraged as the sole way to report expected failures?Because expected failures such as missing data, authorization problems, or validation issues are normal outcomes, not exceptional ones. Exceptions hide these paths, complicate testing, and force callers to guess what may go wrong.
What is the difference between a fault and a contingency?A contingency is an expected outcome the caller can reasonably react to, such as a missing article or validation failure. A fault is an unexpected problem, such as a programming error or corrupted state, which is better handled as an exception.
Why does the chapter introduce separate command and query buses?To reduce coupling and make routing scalable. Instead of injecting many use case interfaces into adapters, adapters depend on a single bus, which resolves the correct handler for each command or query type.
How do commands and queries differ in this architecture?Commands change state and return Either<Error, Void>. Queries retrieve data and return Either<Error, R>, where R is a DTO or projection. This preserves Command-Query Separation.
What role do domain events play in this chapter?Domain events capture something that happened in the domain, such as ArticlePublished. The aggregate generates them, the application handler publishes them after the main work succeeds, and other classes react to them without bloating the handler.

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