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.
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.
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.
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.
Clean Applications with Hexagonal Architecture ebook for free