Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 16
Module 7 · Design problems IV: ATMs, chess and hotels · Chapter 16 of 28
ATM: Sessions, PIN Checks, Cash Dispensing and Reversals
Builds on Solving a Design Problem: Requirements to Tested Code in Six Steps, Design Patterns in TypeScript: Creational, Structural and Behavioural and Vending Machine: States, Payments and Making Change. Next up: Chess: Board, Pieces, Legal Moves and Game End.
Part 1 · Requirements
What the machine must do
An ATM in a Bengaluru office lobby hands out cash only after it has checked the card, the PIN and the account balance. This chapter models that machine as small classes you can run, with the bank hidden behind an interface.
A requirement is a sentence about the system that someone can check. Functional requirements say what the system does, and we write them before any class exists. A PIN is a personal identification number, the secret the customer types to prove the card is theirs. Here is our list.
- The customer inserts a card and types a PIN. The machine checks the PIN with the bank.
- Three wrong PINs in a row make the machine keep the card.
- A signed-in customer can check the balance, which the bank holds.
- A customer can withdraw cash in multiples of ₹100, up to ₹10,000 at a time.
- The machine pays in notes of ₹500, ₹200 and ₹100 from three cassettes, a cassette being a tray that holds notes of one value.
- If the cassettes cannot make the amount, the machine refuses before it touches the account.
- A customer can eject the card and must take it before the next customer starts.
- A technician loads the cassettes.
- If the notes fail to come out after the account was debited, the debit is reversed.
Everything here is our model. The note values, the limit and the three attempts are chosen for this chapter and are not the rules of any bank.
A short prompt such as "design an ATM" 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 debit an account without paying out the notes or reversing the debit. It must never pay notes that were not debited. And a refused action must change nothing: not the account, not the cassettes and not the session.
Money is an integer number of paise, a hundredth of a rupee, so a ₹500 note is 50000. 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 pays out the notes and then debits the account. It looks natural, but if the bank then says no, the cash has already gone and cannot be taken back. The second keeps a copy of each balance inside the machine, so it can answer without calling the bank. That copy goes stale the moment the customer uses another machine, so the bank stays the only place that knows a balance.
| Must | Should | Out of scope |
|---|---|---|
| Insert, PIN, balance, withdraw, eject, load, reversal | Deposit, an audit log | Receipt printing, card readers, encryption of the PIN |
A PIN is a secret, and a real device would protect it, for example by encrypting it inside the keypad. Our model passes the PIN to the bank interface and stops there.
Check yourself
Why does the machine plan the notes before it debits the account?
- Planning can fail when the cassettes are short, and a failed plan has changed nothing.
- Refusing before the debit means there is nothing to undo.
Why does the ATM not keep balances of its own?
- The balance changes at other machines and branches, so a local copy goes stale.
- The bank is the single source of truth, and the ATM asks it.
A customer asks for ₹150. Which of our requirements refuses it?
- The amount must be a multiple of ₹100, and 150 is not.
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 ATM has two actors who start use cases: the customer, who signs in and withdraws, and the technician, who loads the cassettes. The bank is a secondary actor: something the system calls rather than something that calls the system. It has no use case of its own, so it stays off the diagram.
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. Withdrawing always includes dispensing the notes. Refusing for lack of notes extends the withdrawal, and retaining the card extends the PIN step.
The blue boxes are actors and the pills are use cases, with the exceptional ones 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". Formal UML draws the extend arrow the other way, from the extension to the base; here the label carries the meaning.
Read the diagram as a checklist of goals. Each pill becomes a method or two and a few tests, and the red pills show where an unhappy path hangs off a happy one. The technician sits apart at the bottom because loading cassettes shares no step with a customer's session.
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 the card | The machine reads the card and asks for a PIN | A card is already in: refuse |
| Enter the PIN | The bank confirms; the session opens | Wrong PIN: refuse, count it. Third wrong PIN: keep the card |
| Check balance | The bank returns the balance | Not signed in: refuse |
| Withdraw cash | Check the amount, plan the notes, debit, pay out | Bad amount, over the limit, not enough notes, low balance: refuse |
| Eject the card | The card comes out and waits to be taken | Not in a session: refuse |
| Load cassettes | The technician sets the note counts | Not while a customer is using the machine |
Every alternative is a named refusal, and each one must change nothing. A refused withdrawal leaves the account, the cassettes and the session as they were, and we will assert that.
One decision shapes the whole design. The machine plans the notes first, then debits, then moves the hardware. Planning is a pure calculation, so it can fail for free. The debit is a promise from the bank that is hard to take back. The notes are a physical act that cannot be taken back at all. We put the steps that can fail cheaply first and the ones that cannot be undone last, and the final lesson shows what is left when the last step still fails.
Use cases as test names
As in the parking lot chapter, each use case becomes a test.todo name, a map of the work that is reported but not run, and each one becomes a real test by the end.
test.todo('a customer signs in with the right PIN'); test.todo('a customer is locked out after three wrong PINs'); test.todo('a customer checks the balance'); test.todo('a customer withdraws cash in notes'); test.todo('a withdrawal is refused over the limit or no notes'); test.todo('a customer takes the card back'); test.todo('a technician loads a cassette, but not mid-session');
✔ a customer signs in with the right PIN (0.8264ms) # TODO ✔ a customer is locked out after three wrong PINs (0.1186ms) # TODO ✔ a customer checks the balance (0.1156ms) # TODO ✔ a customer withdraws cash in notes (0.1079ms) # TODO ✔ a withdrawal is refused over the limit or no notes (0.1124ms) # TODO ✔ a customer takes the card back (0.0986ms) # TODO ✔ a technician loads a cassette, but not mid-session (0.1001ms) # TODO ℹ tests 7 ℹ todo 7
Output (durations vary)
All seven names are reported as todo, and none counts as passed. 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 withdrawing always dispenses.
- Extend: an exceptional case adds steps under a condition, as the refusal for lack of notes does.
Why is the bank not an actor on the diagram?
- The bank does not start any use case. The ATM calls it, which makes it a secondary actor.
A customer withdraws ₹500 and the cassettes cannot make it. Which use cases run, and what is left afterwards?
- Withdraw cash runs and is extended by the refusal, so dispensing never starts.
- The account and the cassettes are unchanged and the customer is still signed in.
Part 3 · Class diagram
From nouns to classes
Read the requirements again and underline the nouns: ATM, card, PIN, session, balance, bank, cassette, note, amount, keypad, card reader, receipt. Not every noun becomes a class. A useful test is whether the thing has rules to protect or behaviour that varies.
| Noun | Decision | Why |
|---|---|---|
| ATM | Class Atm | Owns the session and orders the steps |
| Session | Fields on Atm | One customer at a time, so a separate class adds nothing |
| Bank | Interface Bank | The real one is remote, so tests need a fake |
| Cash tray and shutter | Interface CashDevice | Hardware is injected, so a test can make it jam |
| Cassette | Class Cassette | Holds a count of one note value |
| All cassettes | Class Dispenser | Plans and commits a payout across cassettes |
| Card, PIN, note, amount | Plain values | A string or a number is enough |
| Keypad, card reader, display | Not classes | Their events become method calls, and errors are the display |
Two choices deserve a reason. The session is not a class because the machine serves one customer at a time, so the phase, the card and the wrong-PIN count are three fields. A second class would only copy them. And the bank and the cash device are interfaces, so that a test can answer "wrong PIN", "balance too low" or "shutter jammed" on demand.
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.
phase: Phaseretained: string[]insertCard(card)enterPin(pin)balance(): Paisewithdraw(amount): NoteCount[]eject(), takeCard()load(value, count)plan(amount): NoteCount[]?commit(picks)load(value, n)count(value)value: Paisecount: numbernext: Cassette?plan(amount), remove(n)verifyPin, balancedebit(card, amount, ref)reverse(ref)present(notes): Promisecode: AtmCodemessage- Atm 1 → 1 Dispenser
- Dispenser 1 → 1..* Cassette
- Atm 1 → 1 Bank (interface)
- Atm 1 → 1 CashDevice (interface)
- Atm 1 → 0..* AtmError
The machine uses exactly one dispenser, one bank and one cash device, and the dispenser holds one or more cassettes. The arrow to AtmError means the machine throws it. Every refusal is an AtmError with a code, so callers and tests branch on the code and never on the message.
A short table links the machine's methods to the use cases they serve, so that no method is left without a goal.
The skeleton in TypeScript
A diagram is only a claim until a compiler reads it. We start with money and errors. The values are plain constants, because enum is not erasable syntax and Node's type stripping rejects it.
export type Paise = number; // In our model: three note values, and these limits. export const NOTE_VALUES: readonly Paise[] = [50000, 20000, 10000]; export const STEP: Paise = 10000; export const PER_WITHDRAWAL: Paise = 1000000; export const MAX_PIN_ATTEMPTS = 3; const inr = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', }); export const rupees = (p: Paise): string => inr.format(p / 100);
The limits live next to the note values, so a change to the rules is a change in one place. Errors come next.
export type AtmCode = | 'BAD_STATE' | 'BAD_AMOUNT' | 'OVER_LIMIT' | 'WRONG_PIN' | 'CARD_RETAINED' | 'INSUFFICIENT_FUNDS' | 'NOT_ENOUGH_NOTES'; export class AtmError extends Error { readonly code: AtmCode; constructor(code: AtmCode, message: string) { super(message); this.name = 'AtmError'; this.code = code; } }
The two interfaces that make the machine testable come next. The bank can verify a PIN, give a balance, debit and reverse a debit by its reference.
export interface Bank { verifyPin(card: string, pin: string): Promise<boolean>; balance(card: string): Promise<Paise>; debit(card: string, amount: Paise, ref: string): Promise<void>; reverse(ref: string): Promise<void>; } export class BankError extends Error { readonly code = 'INSUFFICIENT_FUNDS'; }
BankError carries the one code the bank can answer with for a withdrawal. Type-check the project:
npx tsc -p .
(no output, exit code 0)Output
Why is the session not its own class?
- The machine serves one customer at a time, so the session is a phase, a card and a counter on the machine.
Why is the cash tray an interface?
- A test can then make it succeed or jam, which is how we will test a failed payout.
Part 4 · Sessions and the withdrawal
Five phases
A state machine lists the states, the events that cause moves and the events a state refuses. Our machine has five phases. In idle there is no card. In cardIn there is a card and the PIN is awaited. In authenticated the PIN was right. In inTransaction one action is running. In ejecting the card is out and waits to be taken.
Watch for the machine refusing a withdrawal before the PIN
Read it as steps
Each phase accepts a few actions, and a withdrawal before the PIN is refused.
The scene starts on the refusal. The cardIn phase does not list withdraw, so the machine answers BAD_STATE and nothing moves. A third wrong PIN is the one move the scene leaves out: it keeps the card and returns to idle, which the tests cover.
Why is inTransaction its own phase? A withdrawal waits on the bank and then on the hardware. While it waits, the customer may press another key, and the machine must not start a second action on top of the first. A phase of its own makes that refusal one lookup and not a flag checked in six places.
One withdrawal from start to finish
Now follow a withdrawal of ₹2,300. The customer is signed in. They ask for 230000 paise. The machine first moves to inTransaction, then checks the amount, then asks the dispenser for a plan.
The order matters, and the use case lesson gave the reason. The amount checks and the plan run first because they change nothing. The debit comes next, because the bank has to agree before any note moves. The hardware comes last. Only when the shutter reports success do the cassette counts go down.
| Step | Can fail with | Changes anything? |
|---|---|---|
Enter the phase inTransaction | BAD_STATE | The phase only |
| Check the amount | BAD_AMOUNT, OVER_LIMIT | No |
| Plan the notes | NOT_ENOUGH_NOTES | No |
| Debit the bank | INSUFFICIENT_FUNDS | The account |
| Present the notes | A jam | The tray |
| Commit the cassette counts | Nothing | The cassettes |
Look at the third column. Everything before the debit is free to refuse. The last two steps are the ones the final lesson revisits, because a failure at the tray happens after the account has changed.
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 withdraw before inserting a card, signs in and withdraws ₹2,300.
const { atm } = rig(); const show = (what: string) => console.log(`${what} -> ${atm.phase}`); const text = (ns: NoteCount[]) => ns.map((n) => `${n.count} x ${n.value / 100}`).join(', '); try { await atm.withdraw(100000); } catch (e) { const err = e as AtmError; console.log(`withdraw refused: ${err.code}, ${err.message}`); } atm.insertCard(CARD); show('insert card'); await atm.enterPin('4321'); show('enter PIN'); console.log(`balance ${rupees(await atm.balance())}`); show(`withdraw 2300: ${text(await atm.withdraw(230000))}`); console.log(`balance ${rupees(await atm.balance())}`); atm.eject(); show('eject'); atm.takeCard(); show('take card');
withdraw refused: BAD_STATE, transaction is not accepted while idle insert card -> cardIn enter PIN -> authenticated balance ₹10,000.00 withdraw 2300: 4 x 500, 1 x 200, 1 x 100 -> authenticated balance ₹7,700.00 eject -> ejecting take card -> idle
Output
The first attempt was refused with BAD_STATE because the machine is idle. After the card went in, the machine waited for the PIN. The right PIN signed in. The withdrawal paid four ₹500 notes, one ₹200 note and one ₹100 note, and the balance fell from ₹10,000.00 to ₹7,700.00. Ejecting and taking the card brought the machine back to idle.
In the driver, why does the first withdrawal fail with BAD_STATE and not a balance error?
- In idle there is no card at all, so the phase refuses the action before the bank is asked anything.
Why does the machine plan the notes before it debits?
- Planning can fail and has changed nothing yet, while a debit has to be undone if the notes then fail.
Part 5 · Code: sessions and cassettes
A table of phases
The session needs one guard: given the current phase and an action, where does the machine go, or is the action refused? A table answers that, and it is lighter than a class per phase. The vending machine chapter used one class per state because each state did different work. Here the phases mostly differ in what they accept, so a lookup is enough.
export type Phase = | 'idle' | 'cardIn' | 'authenticated' | 'inTransaction' | 'ejecting'; type Action = | 'insertCard' | 'enterPin' | 'retain' | 'transaction' | 'service' | 'done' | 'eject' | 'takeCard'; // What each phase accepts, and where it leads. const NEXT: Record<Phase, Partial<Record<Action, Phase>>> = { idle: { insertCard: 'cardIn', service: 'idle' }, cardIn: { enterPin: 'authenticated', retain: 'idle', eject: 'ejecting', }, authenticated: { transaction: 'inTransaction', eject: 'ejecting' }, inTransaction: { done: 'authenticated' }, ejecting: { takeCard: 'idle' }, };
NEXT maps each phase to the actions it accepts and the phase each leads to. A missing entry is a refusal. One method turns that into code.
#expect(action: Action): Phase {
const to = NEXT[this.#phase][action];
if (!to) {
throw new AtmError(
'BAD_STATE',
`${action} is not accepted while ${this.#phase}`,
);
}
return to;
}#expect does not move the machine. It only says where the action would lead, or throws BAD_STATE. Each public method then decides when to move. That split matters for the PIN, where a wrong answer must not move at all.
The card methods use it like this.
insertCard(card: string): void { const to = this.#expect('insertCard'); this.#card = card; this.#wrong = 0; this.#phase = to; } async enterPin(pin: string): Promise<void> { const ok = this.#expect('enterPin'); if (await this.#bank.verifyPin(this.#card!, pin)) { this.#phase = ok; return; } this.#wrong += 1; if (this.#wrong >= MAX_PIN_ATTEMPTS) { this.retained.push(this.#card!); this.#card = undefined; this.#phase = this.#expect('retain'); throw new AtmError('CARD_RETAINED', 'too many wrong PINs'); } const left = MAX_PIN_ATTEMPTS - this.#wrong; throw new AtmError('WRONG_PIN', `attempts left: ${left}`); } eject(): void { this.#phase = this.#expect('eject'); } takeCard(): void { this.#phase = this.#expect('takeCard'); this.#card = undefined; }
Cassettes as a chain
The dispenser must turn an amount into a list of notes. The obvious way is greedy: take as many of the biggest note as fit, then as many of the next, and so on. A chain gives that a shape, a variant of the chain of responsibility from the patterns chapter in which each link keeps part of the request. Each cassette takes what it can and hands the rest to the next one, and the last one checks that nothing is left over.
export class Cassette { readonly value: Paise; next: Cassette | undefined; #count: number; constructor(value: Paise, count: number) { this.value = value; this.#count = count; } get count(): number { return this.#count; } // Pure: nothing is removed. Undefined means "cannot be made". plan(amount: Paise): NoteCount[] | undefined { const n = Math.min(Math.floor(amount / this.value), this.#count); const rest = amount - n * this.value; const tail = this.next ? this.next.plan(rest) : rest === 0 ? [] : undefined; if (!tail) return undefined; return n > 0 ? [{ value: this.value, count: n }, ...tail] : tail; } add(n: number): void { this.#count += n; } remove(n: number): void { if (n > this.#count) throw new Error('cassette is short of notes'); this.#count -= n; } }
plan is pure. It reads the counts and removes nothing, so the machine can plan, debit and only then commit. It takes the smaller of what fits and what is in stock, passes the remainder on, and returns undefined when the chain cannot reach zero. On the way back it builds the list of notes, leaving out cassettes that gave none.
Dispenser builds the chain from the stock it is given, sorted from the largest value down, and links each cassette to the next.
export class Dispenser { readonly #cassettes: Cassette[]; constructor(stock: Record<number, number>) { this.#cassettes = Object.entries(stock) .map(([v, n]) => new Cassette(Number(v), n)) .sort((a, b) => b.value - a.value); this.#cassettes.forEach((c, i) => { c.next = this.#cassettes[i + 1]; }); } plan(amount: Paise): NoteCount[] | undefined { const head = this.#cassettes[0]; if (!head) return amount === 0 ? [] : undefined; return head.plan(amount); } commit(picks: readonly NoteCount[]): void { for (const p of picks) this.#find(p.value).remove(p.count); } load(value: Paise, n: number): void { this.#find(value).add(n); } count(value: Paise): number { return this.#find(value).count; } #find(value: Paise): Cassette { const c = this.#cassettes.find((x) => x.value === value); if (!c) throw new Error(`no cassette for ${value}`); return c; } }
The withdrawal
The withdrawal is the order from the last lesson, written as code. #transaction moves to inTransaction before its first await, runs the work, and always returns to authenticated.
async #transaction<T>( work: (card: string) => Promise<T>, ): Promise<T> { this.#phase = this.#expect('transaction'); try { return await work(this.#card!); } finally { this.#phase = this.#expect('done'); } } balance(): Promise<Paise> { return this.#transaction((card) => this.#bank.balance(card)); }
Moving before the await is the same point the vending machine chapter made. A second call that arrives while the bank is being asked already sees inTransaction and is refused. No lock is needed, because nothing can run between the check of the phase and the change of the phase. The finally returns the phase even when the work throws, so a refusal leaves the session usable.
withdraw(amount: Paise): Promise<NoteCount[]> {
return this.#transaction(async (card) => {
if (amount <= 0 || amount % STEP !== 0) {
throw new AtmError('BAD_AMOUNT', 'use multiples of 100 rupees');
}
if (amount > PER_WITHDRAWAL) {
throw new AtmError('OVER_LIMIT', 'above the limit');
}
const notes = this.#dispenser.plan(amount);
if (!notes) {
throw new AtmError(
'NOT_ENOUGH_NOTES', 'cannot make that amount',
);
}
const ref = this.#nextRef();
await this.#debit(card, amount, ref);
await this.#cash.present(notes);
this.#dispenser.commit(notes);
return notes;
});
}Each refusal is thrown before the debit, so the account is untouched. The debit sits in a small method that turns the bank's error into one of ours.
async #debit( card: string, amount: Paise, ref: string, ): Promise<void> { try { await this.#bank.debit(card, amount, ref); } catch (e) { if (e instanceof BankError) { throw new AtmError(e.code, 'balance is too low'); } throw e; } }
Tests
The dispenser's tests need no machine, only a stock of notes.
const full = () => new Dispenser({ 50000: 10, 20000: 10, 10000: 10 }); test('a chain takes the biggest notes first', () => { assert.deepEqual(full().plan(230000), [ { value: 50000, count: 4 }, { value: 20000, count: 1 }, { value: 10000, count: 1 }, ]); });
The others check that planning removes nothing, that impossible amounts have no plan, that 500s and 200s make 900 but not 300, and that the greedy limit is what we described.
✔ a chain takes the biggest notes first (1.207ms) ✔ planning removes nothing, committing does (0.211ms) ✔ an amount no notes can make has no plan (0.1556ms) ✔ 500s and 200s make 900 but not 300 (0.1454ms) ✔ greedy limit: 600 fails with no 100s but 3 x 200 works (0.1104ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output (durations vary)
The session tests drive the machine through rig, a helper that builds one with a fake bank, a fake cash device and full cassettes.
test('withdraw before the PIN is refused, nothing moves', async () => { const { atm, dispenser } = rig(); atm.insertCard(CARD); await assert.rejects(atm.withdraw(100000), { code: 'BAD_STATE' }); assert.equal(atm.phase, 'cardIn'); assert.equal(dispenser.count(10000), 10); }); test('two wrong PINs, then the right one, still sign in', async () => { const { atm } = rig(); atm.insertCard(CARD); await assert.rejects(atm.enterPin('0000'), { code: 'WRONG_PIN' }); await assert.rejects(atm.enterPin('1111'), { message: 'attempts left: 1', }); await atm.enterPin('4321'); assert.equal(atm.phase, 'authenticated'); });
✔ withdraw before the PIN is refused, nothing moves (1.5548ms) ✔ two wrong PINs, then the right one, still sign in (0.2569ms) ✔ the third wrong PIN retains the card (1.2868ms) ✔ while a withdrawal runs, other actions are refused (0.505ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
Output (durations vary)
The withdrawal tests check the effects and, above all, that refusals change nothing.
test('refusals change nothing', async () => { const { atm, bank, dispenser } = rig({ 10000: 0, 20000: 0 }); await signIn(atm); const cases = [ [15000, 'BAD_AMOUNT'], [1100000, 'OVER_LIMIT'], [60000, 'NOT_ENOUGH_NOTES'], ] as const; for (const [amount, code] of cases) { await assert.rejects(atm.withdraw(amount), { code }); } assert.equal(await bank.balance(CARD), 1000000); assert.equal(dispenser.count(50000), 10); assert.equal(atm.phase, 'authenticated'); });
Part 6 · Extensions and trade-offs
Every use case, tested
The use case lesson left seven 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.
test('a customer signs in with the right PIN', async () => { const { atm } = rig(); atm.insertCard(CARD); assert.equal(atm.phase, 'cardIn'); await atm.enterPin('4321'); assert.equal(atm.phase, 'authenticated'); }); test('a customer is locked out after three wrong PINs', async () => { const { atm } = rig(); atm.insertCard(CARD); for (let i = 0; i < 2; i++) { await assert.rejects(atm.enterPin('9999'), { code: 'WRONG_PIN' }); } await assert.rejects(atm.enterPin('9999'), { code: 'CARD_RETAINED' }); assert.deepEqual(atm.retained, [CARD]); }); test('a customer checks the balance', async () => { const { atm } = rig(); atm.insertCard(CARD); await atm.enterPin('4321'); assert.equal(await atm.balance(), 1000000); assert.equal(atm.phase, 'authenticated'); });
The other four cover the notes, the refusals, the eject and the technician's load. The refusal test checks that the limit and a shortage of notes each answer with their own code, and the withdrawal tests from the previous lesson check that nothing else changed.
✔ a customer signs in with the right PIN (1.1816ms) ✔ a customer is locked out after three wrong PINs (1.871ms) ✔ a customer checks the balance (0.2631ms) ✔ a customer withdraws cash in notes (0.5649ms) ✔ a withdrawal is refused over the limit or no notes (0.2742ms) ✔ a customer takes the card back (0.3071ms) ✔ a technician loads a cassette, but not mid-session (3.4944ms) ℹ tests 7 ℹ pass 7 ℹ fail 0 ℹ todo 0
Output (durations vary)
Seven pass and no todo is left. Each name is the sentence the use case lesson wrote, so goals and tests read side by side. The whole suite, including the earlier tests, also passes.
ℹ tests 19 ℹ pass 19 ℹ fail 0 ℹ todo 0
Output: whole suite
When the notes do not come out
The machine we built has a hole. The debit happens before the notes move, and nothing handles a failure after it. A jam is an event the model already has, so we write the test first. These two tests make the fake shutter jam on the next presentation and ask for a withdrawal.
const jammed = async () => { const r = rig(); r.atm.insertCard(CARD); await r.atm.enterPin('4321'); r.cash.jamNext = true; return r; }; test('a jam is reported as DISPENSE_FAILED', async () => { const { atm } = await jammed(); await assert.rejects(atm.withdraw(100000), { code: 'DISPENSE_FAILED', }); }); test('a jam gives the debit back', async () => { const { atm, bank } = await jammed(); await atm.withdraw(100000).catch(() => {}); assert.equal(await bank.balance(CARD), 1000000); });
✖ a jam is reported as DISPENSE_FAILED (3.1479ms) ✖ a jam gives the debit back (0.5181ms) ℹ pass 0 ℹ fail 2 ✖ failing tests: ✖ a jam is reported as DISPENSE_FAILED (3.1479ms) actual: Error: shutter jammed expected: { code: 'DISPENSE_FAILED' }, ✖ a jam gives the debit back (0.5181ms) actual: 900000, expected: 1000000,
Output (paths and durations trimmed)
Both fail, and the numbers say how. The error that came out is the raw shutter jammed, not a code the caller can read. And the account shows 9,00,000 paise where it should show 10,00,000, so the customer is out ₹1,000 for notes they never got. This is the order problem from the use case lesson, now observed.
The fix is a reversal: when presenting fails, ask the bank to undo the debit by its reference. We keep this in a copy of the project, with the new tests next to the old ones. The copy adds 'DISPENSE_FAILED' to AtmCode.
async #present( notes: NoteCount[], amount: Paise, ref: string, ): Promise<void> { try { await this.#cash.present(notes); } catch { try { await this.#bank.reverse(ref); this.#emit('reversed', `${ref} ${amount}`); } catch { this.#emit('unreversed', `${ref} ${amount}`); } throw new AtmError('DISPENSE_FAILED', 'no cash was paid out'); } }
The reference is what makes the reversal safe. The bank looks the debit up by ref and undoes that one debit, and asking twice changes nothing more. The second catch covers the worst case, where the bank cannot be reached. The machine cannot fix that itself, so it reports an unreversed event for a person to settle, and still tells the customer that no cash came out.
Deposits and an audit log
A deposit is the mirror image of a withdrawal, with a different order. The bank is told only after the machine has counted the notes, so the machine never credits money it did not receive. It needs one new method on the Bank interface, credit, and one new method on the machine.
deposit(notes: readonly NoteCount[]): Promise<Paise> { return this.#transaction(async (card) => { let total = 0; for (const n of notes) { if (!NOTE_VALUES.includes(n.value) || n.count < 1) { throw new AtmError('BAD_AMOUNT', 'unknown note value'); } total += n.value * n.count; } const ref = this.#nextRef(); await this.#bank.credit(card, total, ref); this.#emit('deposited', `${ref} ${total}`); return total; }); }
A note of an unknown value is refused before any credit, again a check before a change.
test('a deposit credits the sum of the notes', async () => { const { atm, bank } = rig(); atm.insertCard(CARD); await atm.enterPin('4321'); const total = await atm.deposit([ { value: 50000, count: 2 }, { value: 10000, count: 3 }, ]); assert.equal(total, 130000); assert.equal(await bank.balance(CARD), 1130000); }); test('a note of an unknown value is refused', async () => { const { atm, bank } = rig(); atm.insertCard(CARD); await atm.enterPin('4321'); await assert.rejects(atm.deposit([{ value: 7000, count: 1 }]), { code: 'BAD_AMOUNT', }); assert.equal(await bank.balance(CARD), 1000000); });
✔ a deposit credits the sum of the notes (1.0644ms) ✔ a note of an unknown value is refused (0.7251ms) ℹ tests 2 ℹ pass 2 ℹ fail 0
Output (durations vary)
The audit log is an observer: the machine keeps a list of listeners and tells each one when something happens. withdrawn, reversed, unreversed, deposited and retained are the events. No existing method had to change shape, and a listener can write to a file, a database or a screen.
test('listeners see every money event, in order', async () => { const { atm, cash } = rig(); const seen: string[] = []; atm.on((e) => seen.push(`${e.kind} ${e.detail}`)); atm.insertCard(CARD); await atm.enterPin('4321'); await atm.withdraw(100000); cash.jamNext = true; await atm.withdraw(200000).catch(() => {}); assert.deepEqual(seen, [ 'withdrawn ref-1 100000', 'reversed ref-2 200000', ]); });
✔ listeners see every money event, in order (1.7877ms) ℹ tests 1 ℹ pass 1 ℹ fail 0
Output (durations vary)
Where this design is weak
Every design has costs. The wrong-PIN counter lives in the session, so a person can take the card out, put it back and get three more tries. The count belongs at the bank, per card, and the Bank interface would then grow a method for it. The greedy chain refuses amounts that a smarter search could pay, such as ₹600 without ₹100 notes, and the search from the vending machine chapter would fix that at a cost in complexity. The PIN step has a gap that the transactions do not: enterPin leaves the phase at cardIn while the bank is asked, so two overlapping calls are both accepted, and a phase of its own for checking the PIN would close it. There is no daily limit, which also belongs at the bank. And the machine serves one customer through one process, so a power cut mid-withdrawal leaves the question of what happened to the debit. A durable log of each step, written before the step runs, would answer it.
| Term | Meaning |
|---|---|
| Cassette | A tray that holds notes of one value |
| Chain | Objects that pass the rest of the work to the next one |
| Reversal | A bank request that undoes an earlier debit by its reference |
| 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 |
Why does the reversal use a reference and not an amount and a card?
- A reference names exactly one debit, so reversing it twice cannot give the money back twice.
Why does a deposit credit the bank after counting the notes and not before?
- Crediting first could add money to the account for notes that never arrived.
All chapters · Previous: Car Rental: Fleet, Reservations, Pricing and Returns