Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 11
Module 5 · Design problems II: lockers, vending and blackjack · Chapter 11 of 28
Vending Machine: States, Payments and Making Change
Builds on Solving a Design Problem: Requirements to Tested Code in Six Steps, Design Patterns in TypeScript: Creational, Structural and Behavioural and Parking Lot: Floors, Spots, Tickets and Fees. Next up: Online Blackjack: Shoe, Hands, Dealer Rules and Payouts.
Part 1 · Requirements
What the machine must do
On a Mumbai station platform, a vending machine takes your money, asks you to choose and drops a packet, and sometimes it gives back the wrong coins or nothing at all. This chapter models that machine as classes you can run, so you can see where those failures come from.
As in the parking lot chapter, the functional requirements come first. Here is our list.
- The machine has slots. Each slot holds one item, has a price and has a count of items left.
- It accepts coins of ₹1, ₹2, ₹5 and ₹10, and notes of ₹20, ₹50 and ₹100. Nothing else.
- The display shows the credit, the total money inserted so far.
- A customer selects a slot. If the credit covers the price, the item drops and the machine returns the difference as change.
- Change is paid in coins only, from a limited coin stock. Notes never come back as change.
- A customer can cancel before selecting, and the machine returns exactly what was put in.
- If the machine cannot make the exact change, it refuses the sale and keeps the credit, so the customer can cancel or add coins.
- A technician restocks slots and collects the cash taken.
- If the item does not drop, the machine refunds, stops selling and waits for the technician.
Everything here is our model. The denominations are chosen to make the change problem interesting, and they are not a statement about current Indian coinage.
A short prompt such as "design a vending machine" leaves rules open, so we ask questions. Ask the ones whose answers change a class or a method.
| Question | If the answer is yes | Our answer |
|---|
Quality, numbers and scope
Non-functional requirements say how well the system behaves. Three matter here. The machine must never keep money without giving an item or a refund. It must never give an item that was not paid for. And it must behave the same way for the same inputs, so tests can rely on it.
Money is an integer number of paise, a hundredth of a rupee, so a ₹5 coin is 500. Integers add exactly, while decimals such as 0.1 + 0.2 do not in floating point, and we format as rupees only for display.
We rejected two designs. The first keeps a set of boolean flags such as hasMoney and isDispensing, and every method checks them in a chain of if statements. It works for two modes and becomes unreadable at four, because a new mode means touching every method. The second accepts a sale when change is short and owes the customer the difference. It sounds friendly, but the machine would then carry a debt that nobody can collect from it.
| Must | Should | Out of scope |
|---|---|---|
| Insert, select, change, cancel, restock, collect, jam | UPI as a second way to pay, an audit log | Temperature control, motors, card readers |
Check yourself
A customer inserts a ₹50 note for a ₹15 item. In what denominations can the change come back in our model?
- In coins only, from the coin stock. Notes are never paid back.
Why does the machine refuse a sale it cannot give exact change for?
- Keeping the money and owing the difference would leave the machine with a debt.
- The customer still has their credit and can cancel or add coins.
Why store money as integer paise?
- Integers add exactly. Decimals such as 0.1 + 0.2 do not, in floating point.
Part 2 · Use cases
Actors and use cases
An actor is someone outside the system who uses it. A use case is one goal an actor wants to reach. The machine has two actors: the customer, who pays and chooses, and the technician, who fills it and empties the cash box.
A use case diagram shows actors, their use cases and how those relate. Include means a use case always runs another as part of itself. Extend means an exceptional case adds steps to a base case under a condition. Selecting an item always includes dispensing with change, and the refusal when change cannot be made extends selection.
The blue boxes are actors and the pills are use cases, with the exceptional one in red. An arrow from an actor means the actor starts that use case. Every other arrow runs from a base case to the case it includes or the case that extends it, labelled "includes" or "extended by". The UML chapter explains why the extend arrow is drawn from the base case here.
Read the diagram as a checklist of goals. Each pill becomes one or two methods and a few tests, and the red pill tells us where an unhappy path hangs off the happy one.
The technician sits apart at the bottom because restocking and collecting the cash share no step with a customer's purchase. Keeping the two groups apart also keeps every arrow short: each one runs down to the row just below it. Repairing a jammed machine is not a use case of its own. It is the technician's step that ends the out-of-service wait named in the last requirement, so it sits with the jam alternative above and is tested with the jam.
Flows and alternatives
Each use case gets a short written flow: a trigger, the main steps and the alternatives. Writing alternatives now is cheap. Finding them after the code exists is not.
| Use case | Main flow | Alternatives |
|---|---|---|
| Insert money | A coin or note goes in; credit goes up | Not an accepted denomination: refuse |
| Select an item | Customer picks a slot; machine checks credit and stock | Too little credit, sold out, unknown slot: refuse |
| Dispense with change | Machine plans the change, drops the item, pays the change | No exact change: refuse. Item jams: refund, then out of service until the technician repairs it |
| Cancel and refund | Machine returns what was inserted | Nothing inserted: nothing to return |
| Restock a slot | Technician adds items | Not while a sale is under way |
| Collect the cash | Technician takes the takings; the total resets | Not while a sale is under way |
Every alternative is a named refusal, and each one must change nothing. A refused selection keeps the credit and the stock exactly as they were. We will assert that.
One decision shapes the design. The machine plans the change before it moves the motor. If planning fails, nothing has happened yet, so refusing is free. If we dropped the item first and then found that change was short, we would have to undo a physical action.
Use cases as test names
As in the parking lot chapter, each use case becomes a test.todo name that is reported but not run, and each turns into a real test as the code lands.
test.todo('a customer inserts money'); test.todo('a customer selects an item and gets it with change'); test.todo('a customer cancels and gets the money back'); test.todo('a sale is refused when change cannot be made'); test.todo('staff restock a slot'); test.todo('staff collect the takings once');
✔ a customer inserts money (0.6518ms) # TODO ✔ a customer selects an item and gets it with change (0.0919ms) # TODO ✔ a customer cancels and gets the money back (0.0763ms) # TODO ✔ a sale is refused when change cannot be made (0.0649ms) # TODO ✔ staff restock a slot (0.0827ms) # TODO ✔ staff collect the takings once (0.0688ms) # TODO ℹ tests 6 ℹ todo 6
Output (durations vary)
All six names are reported as todo, and none counts as passed. Later lessons replace them with tests that pass. If a name never gets a test, the requirement behind it was probably missed.
What is the difference between include and extend?
- Include: the base case always runs the included case, as selection always dispenses.
- Extend: an exceptional case adds steps under a condition, as the no-change refusal does.
Why plan the change before moving the motor?
- Planning can fail, and a failed plan has changed nothing yet.
- A dropped item cannot be taken back if the change turns out to be short.
A customer has ₹20 of credit for a ₹15 item, and the coin stock cannot make ₹5. Which use cases run, and what is left afterwards?
- Select an item runs and is extended by the no-change refusal, so dispensing never starts.
- The credit is still ₹20 and the stock is unchanged. The customer can cancel and get the note back, or add coins.
Part 3 · Class diagram
From nouns to classes
Read the requirements again and underline the nouns: machine, slot, item, price, coin, note, credit, change, motor, technician. Not every noun becomes a class. A useful test is whether the thing has rules to protect or behaviour that varies.
| Noun | Decision | Why |
|---|---|---|
| Machine | Class VendingMachine | Owns the credit, slots and coins |
| Mode of the machine | Interface State and four classes | The same action means different things in each mode |
| Slot, item, price | Class Slot | A slot holds an item, a price and a count |
| Coin stock | Class CoinInventory | Guards the counts of each coin |
| Change | Function makeChange | A pure calculation with no state |
| Motor | Interface Motor | Hardware is injected, so a test can fake it |
| Item, coin, note | Plain values | An item is just a name and a coin is a number |
| Technician, customer | Not classes | They call the system, so they stay outside |
Two choices deserve a reason. Change is a function, not a class, because it holds no state and gives the same answer for the same stock and amount. And the motor is an interface so that a test can make it succeed, fail or wait, which is how we will test a jam.
The class diagram
A class diagram shows classes, what they hold and how they relate. Multiplicity is the number on each link end: 1..* means one or more.
state: StateNamecredit: Paiseinsert(amount)select(slotId): Receiptcancel(): Paise[]repair()restock(slotId, n)collectCash(): Paisename: StateNameinsert, select, cancelrepair, restock, collectCashinsert, cancelrestock, collectCashinsert, cancel, selectrefuses everythingrepair, restock, collectCashid, item, pricecount: numbercount(coin)add(coin), remove(coins)snapshot()(amount, stock): coins?drop(slotId): Promise- VendingMachine 1 → 1 State (interface)
- IdleState → State (interface)
- HasMoneyState → State (interface)
- DispensingState → State (interface)
The skeleton in TypeScript
As in the parking lot chapter, a compiler checks the diagram before anything else. We start with money and errors. The denominations are plain arrays, because enum is not erasable syntax and Node's type stripping rejects it.
export type Paise = number; // In our model: coins give change, notes never do. export const COINS: readonly Paise[] = [100, 200, 500, 1000]; export const NOTES: readonly Paise[] = [2000, 5000, 10000]; export const ACCEPTED: readonly Paise[] = [...COINS, ...NOTES]; const inr = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', }); export const rupees = (p: Paise): string => inr.format(p / 100); export const sum = (xs: readonly Paise[]): Paise => xs.reduce((a, b) => a + b, 0);
Coins and notes are separate lists because only coins feed the change stock. Errors come next.
export type VendCode = | 'BAD_STATE' | 'INVALID_MONEY' | 'UNKNOWN_SLOT' | 'SOLD_OUT' | 'NEED_MORE' | 'NO_CHANGE' | 'JAMMED' | 'PAYMENT_DECLINED'; export class VendError extends Error { readonly code: VendCode; readonly refund: Paise[]; constructor(code: VendCode, message: string, refund: Paise[] = []) { super(message); this.name = 'VendError'; this.code = code; this.refund = refund; } }
Every refusal is a VendError with a code from a closed set. A jam also carries the refund, the money that went back to the customer. Callers and tests branch on the code, never on the message. Type-check the project:
npx tsc -p .
(no output, exit code 0)Output
Why is Change a function and not a class?
- It has no state. The same stock and amount always give the same answer.
What does the multiplicity 1 to 1 between the machine and State mean?
- The machine is in exactly one mode at any moment.
A new requirement adds a maintenance mode in which only restocking and repair are accepted. Which parts of this design change?
- One new state class that accepts only restocking and repair, plus its name in the list of state names and one object of that class for the machine to hold.
Part 4 · States and the purchase
The four modes
A state machine lists the states, the events that cause moves and the events a state refuses. Our machine has four modes. In idle there is no credit. In has money there is credit and the customer may add more, cancel or select. In dispensing the motor is running. In out of service the machine waits for a technician.
Watch for the machine refusing a selection before any money is in
Read it as steps
Each mode accepts only some actions, and a selection before any money is refused.
The scene starts on the refusal. The idle state does not override select, so the shared refusal answers BAD_STATE and nothing moves. The same happens for inserting while dispensing: that mode accepts nothing until the item has dropped.
Why is dispensing its own mode? In a real machine the motor takes time. While it runs, a customer may press another button or push in a coin, and the machine must not start a second sale on top of the first. If each mode is its own class, that refusal is one inherited default and not a flag checked in six methods.
One purchase from start to finish
Now follow a purchase. The customer inserts a ₹20 note, which moves the machine to has money. They select slot A1, a ₹15 item. The machine forwards the selection to its current state, and the state does the work.
Watch for the machine handing select to whichever state it is in
Read it as steps
The state checks the sale and plans the change before the motor runs.
The order matters. The state asks for a plan, which validates the slot, the stock and the credit and works out the change, before it changes anything. Only then does it move to dispensing and ask the motor to drop the item. Stock, coins and takings change last, after the motor reports success.
This is the rule from the use case lesson: a check that can fail comes before a change. If the plan fails, the machine is still in has money with the same credit, and the customer can cancel. If the motor fails, the machine refunds and goes out of service, which we test later.
Run the driver
The driver is the demo.ts script from the approach chapter, which runs the core flow once and prints what happened. This one tries to select with no money, inserts a ₹20 note and buys a ₹15 item.
const machine = new VendingMachine( [new Slot('A1', 'Salted peanuts', 1500, 2)], new CoinInventory({ 100: 5, 200: 5, 500: 2, 1000: 1 }), new FakeMotor(), ); try { await machine.select('A1'); } catch (e) { if (e instanceof VendError) console.log('before paying:', e.code); } machine.insert(2000); console.log('state:', machine.state, 'credit:', rupees(machine.credit)); const r = await machine.select('A1'); console.log(r.item, 'for', rupees(r.price)); console.log('change:', r.change.map(rupees).join(' + ')); console.log('state:', machine.state, 'credit:', rupees(machine.credit));
before paying: BAD_STATE state: has-money credit: ₹20.00 Salted peanuts for ₹15.00 change: ₹5.00 state: idle credit: ₹0.00
Output
The selection with no money was refused with BAD_STATE. After the note, the machine was in has-money with ₹20.00 of credit. The sale returned the item and a single ₹5 coin as change, and the machine went back to idle with no credit.
The next lesson writes the classes that produce this output.
In the driver, why does the first select fail with BAD_STATE and not NEED_MORE?
- In idle there is no credit at all, so the mode refuses the action before any check on money.
What does the machine do first when select arrives in has-money?
- It asks for a plan, which checks the slot, the stock and the credit and plans the change.
- Only a successful plan lets it move to dispensing.
Part 5 · Code: states and change
One class per state
The state pattern needs an interface with one method per action. Every state implements all of them, so the machine can forward any action without asking which mode it is in.
export type StateName = | 'idle' | 'has-money' | 'dispensing' | 'out-of-service'; export interface State { readonly name: StateName; insert(m: VendingMachine, amount: Paise): void; select(m: VendingMachine, slotId: string): Promise<Receipt>; cancel(m: VendingMachine): Paise[]; repair(m: VendingMachine): void; restock(m: VendingMachine, slotId: string, n: number): void; collectCash(m: VendingMachine): Paise; }
Writing four classes that each refuse five actions would be a lot of repetition. A base class holds the refusals, and each state overrides only what it allows.
// Every operation is refused unless a state overrides it. abstract class BaseState implements State { abstract readonly name: StateName; insert(_m: VendingMachine, _amount: Paise): void { throw this.no('insert'); } async select(_m: VendingMachine, _slotId: string): Promise<Receipt> { throw this.no('select'); } cancel(_m: VendingMachine): Paise[] { throw this.no('cancel'); } repair(_m: VendingMachine): void { throw this.no('repair'); } restock(_m: VendingMachine, _slotId: string, _n: number): void { throw this.no('restock'); } collectCash(_m: VendingMachine): Paise { throw this.no('collectCash'); } protected no(op: string): VendError { return new VendError('BAD_STATE', `${op} while ${this.name}`); } }
BaseState throws BAD_STATE for every action and names the action and the mode in the message. select is async here, so a refusal arrives as a rejected promise like any other failure of select.
The idle state overrides four actions and nothing else.
class IdleState extends BaseState { readonly name = 'idle'; insert(m: VendingMachine, amount: Paise): void { m.accept(amount); m.transition(HAS_MONEY); } cancel(_m: VendingMachine): Paise[] { return []; } restock(m: VendingMachine, slotId: string, n: number): void { m.fill(slotId, n); } collectCash(m: VendingMachine): Paise { return m.collect(); } }
The state that sells
HasMoneyState is the interesting one, because its select is where the sale happens.
class HasMoneyState extends BaseState { readonly name = 'has-money'; insert(m: VendingMachine, amount: Paise): void { m.accept(amount); } cancel(m: VendingMachine): Paise[] { const back = m.refund(); m.transition(IDLE); return back; } async select(m: VendingMachine, slotId: string): Promise<Receipt> { const plan = m.plan(slotId); // throws before anything changes m.transition(DISPENSING); try { await m.motor.drop(slotId); } catch { const back = m.refund(); m.transition(OUT_OF_SERVICE); throw new VendError('JAMMED', 'the item did not drop', back); } const receipt = m.complete(plan); m.transition(IDLE); return receipt; } }
Three lines carry the design. m.plan runs first and throws before any change. m.transition(DISPENSING) runs before the first await, so the mode changes synchronously, in the same turn as the call. And if the motor fails, the catch block refunds and moves to out-of-service.
That second line has a consequence worth knowing. Because the switch happens before the await, a second select that arrives while the motor runs already sees dispensing and is refused. No lock is needed, because nothing can run between the check of the mode and the change of the mode. The parking lot chapter shows what goes wrong when an await sits between a check and a change.
The plan method in the machine does the checks in order.
plan(slotId: string): Plan {
const slot = this.#slots.get(slotId);
if (!slot) throw new VendError('UNKNOWN_SLOT', slotId);
if (slot.count === 0) throw new VendError('SOLD_OUT', slotId);
const short = slot.price - this.credit;
if (short > 0) throw new VendError('NEED_MORE', `${short} short`);
const change = makeChange(-short, this.#coins.snapshot());
if (!change) throw new VendError('NO_CHANGE', 'cannot make change');
return { slot, change };
}It computes the shortfall, refuses if it is positive, and otherwise asks makeChange for the coins to return.
Making change from a limited stock
The obvious way to make change is greedy: take the biggest coin that fits, then the next, and so on. With plenty of coins of each kind it gives the right answer, as the first test below shows. With a limited stock it can fail even when a solution exists.
// Largest coin first, never backing off. Fast, but it can miss. export function greedyChange(amount: Paise, stock: Stock) { const out: Paise[] = []; let left = amount; for (const coin of [...stock.keys()].sort((a, b) => b - a)) { const n = Math.min(stock.get(coin) ?? 0, Math.floor(left / coin)); for (let i = 0; i < n; i++) out.push(coin); left -= n * coin; } return left === 0 ? out : undefined; }
const stock = new Map([[500, 1], [200, 3], [100, 0]]); const show = (c: number[] | undefined) => c ? c.map(rupees).join(' + ') : 'none'; console.log('stock: one 5, three 2, no 1'); console.log('change for 6, greedy:', show(greedyChange(600, stock))); console.log('change for 6, search:', show(makeChange(600, stock))); console.log('change for 7, greedy:', show(greedyChange(700, stock))); console.log('change for 7, search:', show(makeChange(700, stock))); console.log('change for 3, search:', show(makeChange(300, stock)));
stock: one 5, three 2, no 1 change for 6, greedy: none change for 6, search: ₹2.00 + ₹2.00 + ₹2.00 change for 7, greedy: ₹5.00 + ₹2.00 change for 7, search: ₹5.00 + ₹2.00 change for 3, search: none
Output
Take a stock of one ₹5 coin, three ₹2 coins and no ₹1 coins, and ask for ₹6. Greedy takes the ₹5 coin, is left with ₹1, has no ₹1 coin and gives up. Yet three ₹2 coins make ₹6. For ₹7 both methods agree on ₹5 + ₹2, and ₹3 cannot be made at all, because an odd amount needs the ₹5 coin, which is too big.
The fix is to back off. The search tries the largest coin as many times as it fits, then one fewer, and so on, and recurses on the smaller coins.
// Try the most of each coin, then back off one at a time. export function makeChange(amount: Paise, stock: Stock) { const coins = [...stock.keys()].sort((a, b) => b - a); const walk = (left: Paise, i: number): Paise[] | undefined => { if (left === 0) return []; if (i === coins.length) return undefined; const coin = coins[i]; const have = stock.get(coin) ?? 0; const most = Math.min(have, Math.floor(left / coin)); for (let n = most; n >= 0; n--) { const rest = walk(left - n * coin, i + 1); if (rest) return [...Array<Paise>(n).fill(coin), ...rest]; } return undefined; }; return walk(amount, 0); }
Tests for change and modes
Change gets its own tests, written against plain maps, so they need no machine.
test('with plenty of coins both methods agree', () => { const s = stock({ 100: 5, 200: 5, 500: 5 }); assert.deepEqual(greedyChange(700, s), [500, 200]); assert.deepEqual(makeChange(700, s), [500, 200]); }); test('greedy misses what the search finds', () => { const s = stock({ 100: 0, 200: 3, 500: 1 }); assert.equal(greedyChange(600, s), undefined); assert.deepEqual(makeChange(600, s), [200, 200, 200]); });
The other three cover the zero case, impossible amounts and a check that the search does not change the stock it was given.
✔ with plenty of coins both methods agree (1.6661ms) ✔ greedy misses what the search finds (0.2302ms) ✔ no change is needed for zero (0.1107ms) ✔ an impossible amount is reported, not guessed (0.1292ms) ✔ the search leaves the stock it was given alone (0.1248ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output (durations vary)
The mode tests drive the machine through rig, a helper that builds one with three slots, a coin float and a fake motor.
test('select before paying is refused in idle', async () => { const { machine } = rig(FLOAT); await assert.rejects(machine.select('A1'), { code: 'BAD_STATE' }); assert.equal(machine.state, 'idle'); }); test('a coin moves idle to has-money and cancel returns it', () => { const { machine } = rig(FLOAT); machine.insert(500); assert.equal(machine.state, 'has-money'); assert.deepEqual(machine.cancel(), [500]); assert.equal(machine.state, 'idle'); });
✔ select before paying is refused in idle (1.7657ms) ✔ a coin moves idle to has-money and cancel returns it (0.5089ms) ✔ money that is not accepted changes nothing (0.2062ms) ✔ too little money keeps the credit (0.2095ms) ✔ a sold out or unknown slot is refused (0.1961ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output (durations vary)
The async behaviour needs two tests of its own. The first starts a sale and does not await it yet, checks that the machine is dispensing, and shows insert, cancel and a second select refused. All three refusals are checked before the first await, because an await would let the motor finish and the machine return to idle.
test('while dispensing, new input is refused', async () => { const { machine } = rig(FLOAT); machine.insert(2000); const sale = machine.select('A1'); assert.equal(machine.state, 'dispensing'); assert.throws(() => machine.insert(100), { code: 'BAD_STATE' }); assert.throws(() => machine.cancel(), { code: 'BAD_STATE' }); const second = machine.select('A1'); await assert.rejects(second, { code: 'BAD_STATE' }); const receipt = await sale; assert.deepEqual(receipt.change, [500]); assert.equal(machine.state, 'idle'); });
Part 6 · Extensions and trade-offs
Every use case, tested
The use case lesson left six test.todo names. With the machine in place, each becomes a real test that drives it the way its actor would. These are acceptance tests: they check a goal from the outside, while the earlier tests check single rules.
const FLOAT = { 100: 5, 200: 5, 500: 2, 1000: 1 }; test('a customer inserts money', () => { const { machine } = rig(FLOAT); machine.insert(1000); machine.insert(500); assert.equal(machine.credit, 1500); assert.equal(machine.state, 'has-money'); }); test('a customer selects an item and gets it with change', async () => { const { machine, motor } = rig(FLOAT); machine.insert(2000); const r = await machine.select('A1'); assert.equal(r.item, 'Salted peanuts'); assert.deepEqual(r.change, [500]); assert.deepEqual(motor.dropped, ['A1']); assert.equal(machine.stock('A1'), 1); assert.equal(machine.credit, 0); });
The other four cover cancel and refund, the refusal when change cannot be made, restocking and collecting the cash. The refusal test checks what a refusal means: the credit, the stock and the coin count are the same afterwards.
✔ a customer inserts money (1.5429ms) ✔ a customer selects an item and gets it with change (0.8526ms) ✔ a customer cancels and gets the money back (0.156ms) ✔ a sale is refused when change cannot be made (0.3889ms) ✔ staff restock a slot (0.1399ms) ✔ staff collect the takings once (0.1506ms) ℹ tests 6 ℹ pass 6 ℹ fail 0 ℹ todo 0
Output (durations vary)
Six pass and no todo is left. Each name is the sentence the use case lesson wrote, so goals and tests read side by side.
A second way to pay: UPI
Cash arrives first and the choice comes after. UPI reverses the order: the customer chooses, then pays, then the item drops. That is a different flow, so it needs its own mode, awaiting-payment, and its own action, payByUpi. We add the action to the State interface first and let the compiler find what breaks. This run is on a copy of the project with only that line added.
npx tsc -p . | grep -o "^[a-z./-]*[.]ts" | sort | uniq -c 5 states.tsOutput: errors per file
Five errors, all in one file. The first says BaseState does not implement the whole interface. The other four point at the lines that store each state object as a State, one per state class. Because the states share a base class, one default refusal in BaseState fixes all five, and only IdleState overrides it.
async payByUpi(m: VendingMachine, slotId: string): Promise<Receipt> { const slot = m.slotFor(slotId); // throws before anything changes m.transition(AWAITING_PAYMENT); let paid = false; try { paid = await m.upi.charge(slot.price); } catch { paid = false; } if (!paid) { m.transition(IDLE); throw new VendError('PAYMENT_DECLINED', 'the payment failed'); } m.transition(DISPENSING); try { await m.motor.drop(slotId); } catch { await m.upi.refund(slot.price); m.transition(OUT_OF_SERVICE); throw new VendError('JAMMED', 'the item did not drop'); } const receipt = m.completeUpi(slot); m.transition(IDLE); return receipt; }
The state moves to awaiting-payment before the first await, as select did. A declined or failed payment returns to idle having changed nothing. A jam after the payment is different from a jam with cash, because the customer has already paid, so the machine asks the gateway for a refund before it goes out of service.
test('a UPI payment sells the item with no change', async () => { const { machine, upi } = rig(FLOAT); const r = await machine.payByUpi('A1'); assert.equal(r.item, 'Salted peanuts'); assert.deepEqual(r.change, []); assert.deepEqual(upi.charged, [1500]); assert.equal(machine.stock('A1'), 1); assert.equal(machine.state, 'idle'); }); test('a declined payment changes nothing', async () => { const { machine, upi } = rig(FLOAT); upi.approve = false; await assert.rejects(machine.payByUpi('A1'), { code: 'PAYMENT_DECLINED' }); assert.equal(machine.state, 'idle'); assert.equal(machine.stock('A1'), 2); });
Out of service and an audit log
The out-of-service mode already exists from the jam, and its tests show the whole path: a jam refunds the cash, the machine refuses new coins and a technician's repair returns it to idle. What the operator also wants is a record of what happened. That is an observer: the machine keeps a list of listeners and calls each one when its mode changes.
test('a listener sees every state change in order', async () => { const { machine } = rig({ 100: 5, 200: 5, 500: 2 }); const log: string[] = []; machine.onTransition((from, to) => log.push(`${from} > ${to}`)); machine.insert(2000); await machine.select('A1'); assert.deepEqual(log, [ 'idle > has-money', 'has-money > dispensing', 'dispensing > idle', ]); });
✔ a listener sees every state change in order (1.7728ms) ℹ tests 1 ℹ pass 1 ℹ fail 0
Output (durations vary)
transition is the only place the mode changes, so it is the only place that notifies. A purchase with a ₹20 note produces three entries, and none of the state classes had to change. The whole extended project, with the original tests, passes.
ℹ tests 24 ℹ pass 24 ℹ fail 0 ℹ todo 0
Output: whole extended suite
Where this design is weak
Every design has costs. The state objects are shared constants, so they cannot hold per-machine data, and everything they need is passed in. Adding an action means touching the interface and the base class, though the compiler found both for us. The search for change is exponential in the worst case: when an amount cannot be made it tries every combination, which took 341 calls for four kinds of coin with three of each and 21,845 for seven kinds, so a large stock would need a table instead. Inserted coins join the stock only after a sale, so the machine can refuse a sale that the customer's own coins would have made possible, and a different rule would change that. And the model has one process and no storage: a power cut loses the credit, which a real machine would write down.
| Term | Meaning |
|---|---|
| State pattern | One class per mode, all with the same methods, chosen at run time |
| Invariant | A condition that must always hold, such as credit equal to the sum inserted |
| Greedy | Taking the best-looking choice at each step without backing off |
| Observer | A list of listeners that an object calls when something happens |
| Acceptance test | A test of a goal from the outside, through the public methods |
What extra step does a UPI jam need that a cash jam does not?
- The customer already paid, so the gateway must be told to refund.
Why is the audit log written in transition and not in each state?
- transition is the only place the mode changes, so one hook sees every change.
A teammate moves m.transition(AWAITING_PAYMENT) in payByUpi to after the await on the charge. What goes wrong?
All chapters · Previous: Parcel Locker Service: Slots, Pickup Codes and Expiry