Workbench / The TiffinBox Build
S2 · V1·02
The Domain Model
Volume 1, chapter 02. TiffinBox gets its core vocabulary as code: `Money`, `Dish`, `OrderLine`, `Order`, and the order lifecycle as a sealed set of states moved by a pure transition function. Illegal states become unrepresentable, the compiler checks every transition when a state is added, and real JUnit tests replace stage 1's hand-rolled checks. You'll weigh exceptions against result types, and object-oriented against functional modelling, and record both decisions.
Stage 2: the domain model
The brief
What you'll build. A core library, the heart that every later part of TiffinBox (the server in stage 9, the Spring service in Volume 3, the apps in Volumes 2 and 22) will use:
Money: rupees as integer paise, never negative, with overflow-checked arithmetic;DishandOrderLine: validated on construction, so an invalid one can't exist;Order: immutable, holding its lines and its current status;OrderStatus: a sealed set of states (Placed,Accepted,Ready,Delivered,Cancelled), each carrying only the data that exists in that state;Transition.apply(state, event): the whole order lifecycle as one pure function that returns either the next state or a reason for refusing.
Plus a JUnit 5 test suite that runs in the build and fails it on any error.
Why a real company needs this. Most production bugs in ordering systems aren't clever algorithms gone wrong. They're states that should never exist:
- an order marked delivered that was never accepted;
- a refund larger than the payment;
- a quantity of zero;
- a cancellation after the food left the kitchen.
Teams usually guard against them with checks scattered across controllers, services and SQL. A domain model makes them impossible in one place, so every caller gets the guarantees for free.
Why now. Chapter 02 gives you exactly the tools: types and values, immutability, sum types and exhaustive matching, functions, error models, and testing. And stage 1's Paise and Stats were already a tiny domain model hiding inside a CLI. Now it gets its own module, before anything else depends on the wrong shape.
What you'll have at the end.
core/with seven small types and a lifecycle you can explain on one page;- a test suite (11 tests to start) wired into
build.sh; tbxupdated to useMoney;- ADR-0003 (how the lifecycle is modelled) and ADR-0004 (the error model).
Theory to own
- Value against reference semantics.
Orderholds aList<OrderLine>. If a caller passes in a list and later adds to it, what happens to the order? What does "a record is immutable" actually guarantee? (Chapter: "State, immutability, values and ownership"; the Companion's "two models of a variable".) - Sum types and exhaustiveness. Why model status as a sealed interface of records, rather than an
enumplus nullable fields (acceptedAt,prepMinutes,cancelReason)? What does the compiler do when a new state is added? (Chapter: "Enums and sum types"; "Conditionals and multi-way branches".) - Error models. "Kitchen tries to mark an order ready before accepting it." Is that an exception, an error value, or a result? What about
new OrderLine(dish, -3)? (Chapter: "Error handling"; Companion, "four ways for a waiter to report a problem".) - Pure functions. Why should
Transition.applytake the time from the event rather than callingInstant.now()? (Chapter: "State and side effects".) - Integer arithmetic. What does
Math.addExactdo that+doesn't, and why does that matter for money? (Chapter: "Arithmetic, division and the overflow question".) - Testing. What makes a test of
Transitioneasy (no mocks, no setup)? What would make it hard? (Chapter: "Testing fundamentals".)
Build it
Step 1: a module of its own
Create core/ at the repository root, beside tools/:
tiffinbox/
├── core/
│ ├── build.sh
│ ├── src/in/tiffinbox/core/ Money, Dish, OrderLine, Order, OrderStatus, OrderEvent, Transition
│ └── test/
│ ├── RunTests.java runs JUnit, exits non-zero on failure
│ └── in/tiffinbox/core/CoreTest.java
├── lib/junit-platform-console-standalone.jar (download once; Volume 3 replaces this with Gradle)
└── tools/tbx/ now depends on core
Checkpoint 1. Why a separate module for the domain, when tbx is its only user today?
Step 2: Money as a value type
Checkpoint 2. Write Money: a record over long paise. It refuses negatives, adds and multiplies with overflow checks, offers a "subtract but never below zero" for discounts, and prints with ASCII digits. Decide what happens on overflow.
Step 3: dishes, lines and orders that can't be invalid
Checkpoint 3. Write Dish(id, name, price), OrderLine(dish, quantity) (1 to 20) and Order(id, kitchenId, lines, status) (at least one line). Make sure a caller who keeps a reference to the list they passed in can't change the order afterwards.
Step 4: the lifecycle as a sealed type and a pure function
The order goes Placed → Accepted → Ready → Delivered, and can be Cancelled from Placed or Accepted. Events are KitchenAccepted(prepMinutes), FoodReady, HandedOver and CancelRequested(reason), each with a timestamp.
Checkpoint 4. Model states and events as sealed interfaces of records. Write Transition.apply(state, event) returning Moved(newState) or Rejected(reason). Then add a new state, OutForDelivery, without updating apply, and compile. What happens?
Step 5: tests that run in the build
Checkpoint 5. Write JUnit 5 tests for: exact addition, negative money, overflow, the discount floor, printing, order totals, the defensive copy, invalid quantities, the happy-path lifecycle, a rejected transition, and terminal states rejecting everything. Then wire them into build.sh so any failure stops the build.
Step 6: point tbx at the core
Replace tbx's Paise arithmetic with Money: parse amounts to Money, accumulate with plus, and format with toString. Keep stage 1's checks passing; they're your regression suite. Add -cp ../../core/out/tiffinbox-core.jar to tbx's build.
Senior and architect lens
1. Make illegal states unrepresentable, then stop checking. Every constructor that validates removes a check from every caller, forever. The test of a good domain model is how few if (x == null) and if (quantity <= 0) checks the rest of the code needs. The price is up-front design, and a little friction when data really is incomplete (a draft order). Model that friction explicitly (a DraftOrder type) instead of loosening Order.
2. Two paradigms, one decision: ADR-0003. There are two classic ways to model a lifecycle:
- Object-oriented (the State pattern): each state is a class with methods (
placed.accept(…),accepted.markReady(…)). Adding a new state is easy (one new class). Adding a new event means editing every state class. - Functional (this stage): states and events are plain data, and one function decides. Adding a new event means editing one function; adding a new state makes the compiler list every function to update.
This is the expression problem in miniature: each style makes one kind of change cheap. Orders gain new events (refund requested, rating left, delivery partner assigned) more often than new states, and a single function is far easier to review, test exhaustively (stage 5) and persist as an event log (stage 8). So the functional model wins here. Record that reasoning, and the revisit trigger: if states start carrying complex behaviour of their own, reconsider.
3. An error model for the whole system: ADR-0004. Decide once, write it down, and apply it everywhere:
| Kind of failure | Representation | Handled where |
|---|---|---|
| business rule refused (illegal transition, sold out) | sealed result (Outcome.Rejected) |
the immediate caller, shown to a person |
| invalid input from a person or file | rejected at the boundary (stage 1's parser), before domain types are built | the edge (CLI, later the HTTP layer) |
| programming error (negative quantity reaching a constructor) | unchecked exception | nowhere: fix the bug |
| infrastructure failure (later: disk, network) | checked or unchecked exception, by layer | once, at the request boundary |
The key line: domain constructors throw, domain operations return results. Constructors throw because invalid data reaching them is a bug. Operations return results because refusing is normal business.
4. Immutability is a concurrency strategy you get for free. Stage 9 serves many requests at once, and Volume 3 adds threads everywhere. Immutable Orders can be shared across threads with no locks, cached without defensive copies, and put on an event log without fear of later edits. Making them immutable now costs a few allocations. Making them immutable later costs a migration.
5. Keep the core free of time, I/O and frameworks. No Instant.now(), no logging, no annotations from any framework in core/. That's the rule that lets the same code run in a CLI, a hand-written server, Spring, a test, or a replay of last month's events. Volume 3, chapter 37 (hexagonal architecture) gives this rule its formal name.
What breaks first, and when it's addressed:
| Pressure | What breaks | Where it's addressed |
|---|---|---|
| discounts and campaigns | total() on Order is too simple |
stages 5 and 10 |
| looking up dishes by ID, fast | dishes are just values; nothing indexes them | stage 3 |
| persisting orders and replaying history | the lifecycle needs an event log | stage 8 |
| JSON in and out | records need mapping, and the wire format must not leak domain changes | stage 9 and Volume 3 (DTOs) |
| several kitchens editing the same order concurrently | immutable values need a concurrency control at the store | Volume 3 (optimistic locking), Volume 4 |
Evidence
core/build.shruns the tests and fails the build on any failing test (show a deliberately broken test failing it).- An attempt to construct each invalid value (negative money, quantity 0 and 21, blank dish name, empty order) throws, with a test for each.
- The defensive-copy test passes, and fails if you remove
List.copyOf(try it). - Adding a state without handling it fails compilation (paste the real error into the README).
- Every state and event pair (5 states × 4 events = 20) has an expected outcome in a table in the README. It's the input to stage 5's exhaustive check.
tbxnow usesMoney, and stage 1's checks still pass.- ADR-0003 (lifecycle as sealed states plus a pure transition function) and ADR-0004 (the error model) are committed.
Carry forward
Moneyis the only way money moves through TiffinBox from now on. Never adouble, never a barelongin a public signature.- The sealed
OrderStatusandTransition.applybecome the source of truth for the lifecycle. Stage 5 checks them exhaustively, stage 8 stores the events that drive them, and Volume 3's Spring service calls the same function. - Domain constructors throw; operations return results (ADR-0004). Volume 3's error handling and HTTP problem details build on this split.
- No clock, no I/O, no framework in
core/. Guard this rule now; Volume 3 adds an architecture test that enforces it.