Design an ATM. A customer inserts a card, enters a PIN, then checks a balance, withdraws or deposits cash. The machine talks to the bank and holds a limited stock of notes.
The customer **inserts a card** and enters a **PIN**; three wrong PINs keep the card.
A withdrawal must be possible with the **notes the machine holds** (for example 2000, 500, 100).
A **daily limit** applies per card.
If the bank call fails, the customer must **not** lose money or get cash they were not debited for.
Stage 1: Cards, accounts and the bank
Name the things and keep the bank behind an interface.
The ATM does not own accounts: the bank does. Without a boundary the machine ends up holding bank logic. `BankService` is an interface with `verifyPin`, `balance`, `debit` and `credit`. `Session` tracks the card and PIN attempts. Every call carries a transaction id, so a retry after a timeout cannot debit twice. A network call per action is slow but correct. Caching the balance would risk showing a stale number.
Stage 2: The ATM and its states
Allow the right actions at the right time.
How do we stop someone withdrawing before entering a PIN? `ATMState` with `IdleState` (waits for a card) and `AuthenticatedState` (allows balance and withdraw). Each method is refused in the wrong state. The ATM never checks `if (loggedIn && ...)`. Wrong actions simply do nothing (**State**). More states (PIN entry, out of service) follow the same pattern; keep their count small so transitions stay readable.
Stage 3: Dispensing notes: Chain of Responsibility
Make the right notes come out.
A withdrawal of 3500 must become notes the machine actually has. A chain of `NoteHandler`s from large to small. Each takes as many of its note as it can and passes the remainder on. `canDispense` checks the chain before the bank is debited. A new note size is one more handler (**Chain of Responsibility**). Checking before debiting keeps us from taking money for cash we cannot give. A greedy chain gives fewest notes for normal denominations but can fail for odd ones. Check the stock first.
Stage 4: Transactions that survive failure
Debit before dispense, and undo on a jam.
If the cash jams after the debit, the customer is out of pocket. `withdraw` creates a `Transaction`: check the notes, debit through the bank with the transaction id, then dispense. If dispensing fails, `rollback` credits the same id. The order is fixed: check, debit, dispense. A failure at any step leaves a record that can be settled. A crash between debit and dispense still needs the bank to reconcile by transaction id at the end of the day.