Design patterns and domain modeling
Explicit state machine
Validate lifecycle transitions; not GoF State objects. Executed Java 21 fixture.
Formal Syntax & Structure
java syntaxjava
transition(from,to)Working Example
Example Snippetjava
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()); }}