Design trade-offs
What you will learn
Patterns are tools for recurring design problems, not a checklist. Evaluate the cost of indirection, the stability of the contract and the ease of testing before adding a pattern. Behavioral patterns organize changes in policy, state, communication and requests.
- Compare a direct state machine with state objects.
- Use command and observer boundaries without confusing them with durable messaging.
- Choose a design using observable evidence and maintenance trade-offs.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. All examples in this chapter are standalone, single-threaded Java 21 models unless stated otherwise.
A small explicit state machine
public class Main { enum Status { DRAFT, CONFIRMED, SHIPPED } static class Order { private Status state = Status.DRAFT; void confirm() { transition(Status.DRAFT, Status.CONFIRMED); } void ship() { transition(Status.CONFIRMED, Status.SHIPPED); } void transition(Status from, Status to) { if (state != from) throw new IllegalStateException("transition"); state = to; } Status state() { return state; } } public static void main(String[] args) { var order = new Order(); order.confirm(); try { order.confirm(); throw new AssertionError(); } catch (IllegalStateException expected) { System.out.println("rejected"); } order.ship(); System.out.println(order.state()); }}Expected output:
rejectedSHIPPEDThis is an explicit finite state machine, not the GoF State object pattern. For three stages and two operations it is easy to inspect. If state-specific behavior grows, extract state objects while retaining the transition checks.
Behavioral pattern map
Strategy varies a policy; State varies behavior according to the lifecycle of an object. Command represents a request as an object; Observer notifies registered listeners. Template Method fixes an algorithm outline and lets subclasses vary steps; composition is an alternative. Iterator traverses without exposing storage. Chain of Responsibility passes a request through handlers; Mediator coordinates interactions. Visitor separates operations over a stable set of types, and Memento captures state for restoration. Each adds a different kind of indirection.
Choosing a design
A small enum and switch may express a closed lifecycle more clearly than a class per state. State objects can help when many operations vary independently by lifecycle stage. Observer makes local notification flexible, but synchronous listeners can fail or block callers. Commands make a request explicit but do not imply undo, persistence, retry safety or authorization. For durable events, use the transaction and messaging mechanisms discussed earlier.
Review the trade-off
Sketch the dependency direction in text: caller -> policy port <- infrastructure implementation. For an aggregate: caller -> root -> internal state; event snapshot -> application publisher. Ask which dependency changes, what test catches a broken contract, and whether a simpler design would survive the same change. Use measured profiling rather than assuming patterns improve performance.
Command as a validated request
public class Main { record Add(int amount) { Add { if (amount <= 0) throw new IllegalArgumentException("amount"); } void execute(Counter c) { c.add(amount); } } static class Counter { private int value; void add(int n) { value = Math.addExact(value, n); } int value() { return value; } } public static void main(String[] args) { var counter = new Counter(); var commands = java.util.List.of(new Add(2), new Add(3)); for (Add command : commands) command.execute(counter); System.out.println(counter.value()); }}Expected output:
5The command holds the validated request and knows how to invoke its receiver. Repeating the same command adds twice, so replay is not idempotent. A durable command queue needs its own identity, transaction and authorization policies.
Observer with explicit local delivery semantics
public class Main { static class Subject { private final java.util.List<java.util.function.Consumer<String>> listeners = new java.util.ArrayList<>(); void subscribe(java.util.function.Consumer<String> listener) { listeners.add(java.util.Objects.requireNonNull(listener)); } int publish(String message) { int failures = 0; for (var listener : java.util.List.copyOf(listeners)) { try { listener.accept(message); } catch (RuntimeException failure) { failures++; } } return failures; } } public static void main(String[] args) { var subject = new Subject(); var seen = new java.util.ArrayList<String>(); subject.subscribe(seen::add); subject.subscribe(s -> { throw new IllegalStateException("listener"); }); subject.subscribe(s -> seen.add("audit:" + s)); System.out.println(subject.publish("reserved")); System.out.println(seen); }}Expected output:
1[reserved, audit:reserved]This chosen synchronous policy continues after a listener throws and reports the number of failures. It is a local teaching example: it does not persist, retry, unsubscribe or isolate slow listeners. Production notification needs explicit lifecycle and failure reporting.
Common mistakes
Do not introduce patterns just because they appear in a catalog. Do not equate an in-memory observer with reliable messaging. Avoid adding undo to a command if the business operation cannot safely be reversed. Use regression tests before replacing an understandable state machine.
Practice
Model a booking with OPEN, CONFIRMED and CANCELLED states. Allow confirmation or cancellation from OPEN, and reject later changes. Confirm one booking and cancel another; verify the second transition fails without modifying either result.
Expected output:
rejectedCONFIRMEDCANCELLEDCompare with the manual review criteria.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Design trade-offs — knowledge check
Design and domain modeling reasoning.
When might an enum state machine be preferable?
What distinguishes a command from a domain event?
Does an observer guarantee durable delivery?
Which pattern captures restorable state?
What is a good reason to refactor a working design?