liveBook · Manning

Command-query separation

As explained in Clean Applications with Hexagonal Architecture

A software design principle that separates operations that change state from operations that return information without changing state.

Commands change state; queries return data. Keeping those jobs separate gives handlers focused responsibilities and prevents callers from retrieving domain objects through command interfaces. section 4.6 section 4.4.3

Keep the boundary explicit in use-case contracts:

  • Return Either<Error, Void> from a command: its right side signals success without returning business data, while its left side exposes typed failure. section 4.3.1
  • Return data from a query. If a caller needs information after a command, give that request its own query use case and handler. section 4.6 section 4.4.3
  • Use @Transactional(readOnly = true) on query handlers and an ordinary transactional boundary on command handlers to reinforce the distinction at runtime. section 6.3.5

Publishing an article

A publish command can load an article, invoke its domain behavior, and save it while returning Either<Error, Void>. A caller that later needs article data uses a separate query. section 4.4.3 section 4.6

Listing 6.10 @Transactional to enforce CQS
@ApplicationService
@RequiredArgsConstructor
@Transactional(readOnly = true) #A
final class GetArticleByIdHandler
  implements GetArticleByIdUseCase {
  // ...
}

The query handler’s read-only transaction makes an attempted repository write fail at the database level. section 6.3.5

How Clean Applications with Hexagonal Architecture covers it

How deep it goes
Defines command and query contracts, shows typed failures, and extends separation to read-only transaction enforcement.
Examples
Contrasts article publication as a command with article lookup as a query.
What you can do after
Apply CQS with typed command outcomes, separate query use cases, and read-only query transactions.
How it connects
Connects commands and queries with handlers, Either, transactions, and domain objects.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clean Applications with Hexagonal Architecture. The section links point to the parts of the book it draws on.