These are the notes for Low-Level Design (LLD) episode 64: the ATM, the next classic machine-coding problem after the vending machine. This time the money belongs to a bank account, so mistakes hurt more. We gather the ATM requirements, find the entities (Card, Account, Bank, ATM, CashDispenser, Transaction), watch the obvious boolean-flag design give cash to a wrong PIN, then build ATM states with the State pattern and authentication with a PIN checked by the bank. Then the cash dispenser as a Chain of Responsibility for note denominations, the three transaction types (withdraw, deposit, balance enquiry), and transaction rollback with careful failure handling.
How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly. The ATM, its notes, card numbers, PINs and balances are made up for teaching.
1. The problem: the ATM outside the market
| What happens | What went wrong in the code | Fixed by |
|---|---|---|
| A stranger with your lost card types a wrong PIN, and cash comes out | withdraw forgot to check a boolean flag |
ATM states (State pattern) |
| The stranger can guess PINs forever | Nobody counts wrong tries | The bank authenticates and blocks after 3 |
| Rs 2600: which notes? | Note sizes hard-coded in one method | Chain of Responsibility, one link per note |
| "Debited Rs 2000", but the machine jammed and gave nothing | Debit happened, dispensing failed, nobody undid the debit | Transaction rollback |
2. Requirements
An ATM (automated teller machine) is a machine that does a bank teller's job: it gives and takes cash and shows your balance, without a person at a counter.
A requirement is something the system must do, agreed before coding (episode 55). ATM requirements for today:
- Insert a card, enter the PIN, choose a transaction.
- Transactions: withdraw cash, deposit cash, balance enquiry (just show the balance).
- The bank checks the PIN; 3 wrong PINs → the card is blocked (and kept by the machine).
- Withdraw only up to the balance, and only in notes the machine really has. Our made-up ATM holds Rs 500, Rs 200 and Rs 100 notes.
- The golden rule: never take money from the account without giving the cash. If anything fails after the debit, roll back.
Out of scope today: transfers (practice 1), mini statements, cards of other banks.
| Clarifying question | Our assumption |
|---|---|
| Who checks the PIN? | The bank. The ATM never stores PINs |
| How many tries? | 3 wrong PINs block the card |
| Which notes? | 500, 200, 100 (our machine's choice) |
| Any amount? | Multiples of 100 only, up to the balance |
| What if the notes can't make the amount? | Refuse before debiting |
| What if the dispenser jams after debiting? | Roll back: credit the amount back and tell the customer |
PIN (personal identification number): a short secret number only the card owner knows, for example 4321.
Transaction: one complete job the customer asks for, such as "withdraw Rs 2000". It must happen completely or not at all.
Balance: how much money is in the account right now.
3. Entities
An entity is a thing in the problem with its own data and rules. The nouns in the requirements give us six:
| Entity | What it is | Data | Example |
|---|---|---|---|
Card |
A key that says which account; it holds no money | card number | Card("4111") |
Account |
Where the money lives, at the bank | id, balance | Account("SB-001", 5000) |
Bank |
Knows every PIN and account; the ATM only asks it | PINs, failed tries, accounts | bank.authenticate(card, 4321) |
ATM |
The machine: holds the current state, the card in it, the dispenser | state, card, account | atm.insert(card) |
CashDispenser |
The box of notes inside, with rollers that push them out | notes of each denomination | 500 × 4, 200 × 5, 100 × 2 |
Transaction |
What the customer asked for | type and amount | Withdraw(2000) |
4. The obvious way: boolean flags (and how they break)
A boolean flag is a true/false variable that remembers one fact, like cardInserted. The obvious design uses two:
class ATM { // the obvious way: boolean flags
boolean cardInserted, pinVerified; int balance = 5000; final int pin = 4321;
void insertCard() { cardInserted = true; System.out.println("card in"); }
void enterPin(int p) {
if (!cardInserted) { System.out.println("insert card first"); return; }
pinVerified = (p == pin);
System.out.println(pinVerified ? "PIN ok" : "wrong PIN");
}
void withdraw(int amount) {
if (!cardInserted) { System.out.println("insert card first"); return; }
balance -= amount; // forgot to check pinVerified!
System.out.println("take Rs " + amount + ", balance Rs " + balance);
}
void ejectCard() { cardInserted = false; System.out.println("card out"); }
}
public class Main {
public static void main(String[] args) {
ATM atm = new ATM();
atm.insertCard(); atm.enterPin(1111); atm.withdraw(2000); // a stranger, wrong PIN
atm.ejectCard();
System.out.println("pinVerified = " + atm.pinVerified + ", balance = " + atm.balance);
}
}
Real output:
card in
wrong PIN
take Rs 2000, balance Rs 3000
card out
pinVerified = false, balance = 3000
The ATM printed wrong PIN and then gave Rs 2000 anyway: withdraw checks cardInserted but forgets pinVerified. Nothing warns you. That is the lost-card story.
Why it failed
- Two flags make four combinations, and some are nonsense ("no card, but PIN verified").
- Every method must check every flag. The day one method forgets, money walks out.
- The ATM compares the PIN itself, so the secret sits in every machine. A real ATM must never do that.
5. ATM states and authentication with a PIN
ATM states are the situations the machine can be in, each with its own allowed buttons:
| State | Screen shows | Allowed | Everything else |
|---|---|---|---|
Idle |
"Please insert your card" | insert card | "not allowed now" |
HasCard |
"Enter your PIN" | enter PIN, eject | "not allowed now" |
Authenticated |
"Choose a transaction" | withdraw, deposit, balance, eject | — |
Authentication means proving you are who you claim to be. At an ATM, you prove you own the card by typing its PIN. The bank does the check and answers one of three things: OK, WRONG or BLOCKED (after 3 wrong tries).
We use the State pattern (episode 37): each state is its own class implementing one State interface; the ATM is the context that holds the current state and passes every button press to it (delegates). Here the interface's default methods (episode 3) answer "not allowed now", so each state writes only the buttons it really allows. The states are records (episode 3): small classes whose fields are fixed at creation.
import java.util.*;
enum PinResult { OK, WRONG, BLOCKED }
class Bank { // the BANK checks the PIN, never the ATM
private final Map<String, Integer> pins = Map.of("4111", 4321), fails = new HashMap<>();
PinResult authenticate(String card, int pin) {
if (fails.getOrDefault(card, 0) >= 3) return PinResult.BLOCKED;
if (pins.get(card) == pin) { fails.remove(card); return PinResult.OK; }
return fails.merge(card, 1, Integer::sum) >= 3 ? PinResult.BLOCKED : PinResult.WRONG; } }
interface State { // one method per button; default = "not now"
default void insert(String card) { say("card already inside"); }
default void pin(int p) { say("insert card first"); }
default void withdraw(int amt) { say("not allowed now"); }
default void say(String s) { System.out.println(getClass().getSimpleName() + ": " + s); } }
class ATM { final Bank bank = new Bank(); State state = new Idle(this); String card; int bal = 5000; }
record Idle(ATM atm) implements State {
public void insert(String c) { atm.card = c; atm.state = new HasCard(atm); say("enter PIN"); } }
record HasCard(ATM atm) implements State {
public void pin(int p) { switch (atm.bank.authenticate(atm.card, p)) {
case OK -> { atm.state = new Authenticated(atm); say("PIN ok"); }
case WRONG -> say("wrong PIN, try again");
case BLOCKED -> { atm.state = new Idle(atm); say("card blocked and kept"); } } } }
record Authenticated(ATM atm) implements State {
public void withdraw(int amt) { atm.bal -= amt; say("take Rs " + amt + ", balance " + atm.bal); } }
public class Main { public static void main(String[] args) {
ATM atm = new ATM();
atm.state.withdraw(500); atm.state.insert("4111"); atm.state.pin(1111); // a stranger
atm.state.withdraw(2000); atm.state.pin(2222); atm.state.pin(3333); // keeps guessing
atm.state.insert("4111"); atm.state.pin(4321); }} // now the right PIN
Real output:
Idle: not allowed now
Idle: enter PIN
HasCard: wrong PIN, try again
HasCard: not allowed now
HasCard: wrong PIN, try again
HasCard: card blocked and kept
Idle: enter PIN
HasCard: card blocked and kept
Read it line by line: withdrawing in Idle is not allowed; the card goes in; a wrong PIN; withdrawing in HasCard is still not allowed (no cash without the PIN); two more wrong PINs and the bank answers BLOCKED; afterwards even the right PIN gets card blocked and kept, because the bank remembers.
Idle ──insert card──▶ HasCard ──PIN OK──▶ Authenticated ──eject──▶ Idle
│ ▲ │
└──┘ wrong PIN └─ withdraw / deposit / balance (stays)
└──3rd wrong PIN (card kept) / eject──▶ Idle
6. The cash dispenser: Chain of Responsibility for note denominations
A denomination is the face value of a note: Rs 500, Rs 200, Rs 100. The cash dispenser must turn an amount into notes, using only the notes really inside. The usual way is greedy: the biggest note first, as many as fit and as the box has, then the next size. For Rs 2600 with four 500s: 500 × 4 = 2000, then 200 × 3 = 600.
The obvious way: every note size hard-coded in one method
public class Main {
static int n500 = 4, n200 = 5, n100 = 2;
static String dispense(int amount) { // every note size hard-coded in one method
int a = Math.min(amount / 500, n500); amount -= a * 500;
int b = Math.min(amount / 200, n200); amount -= b * 200;
int c = Math.min(amount / 100, n100); amount -= c * 100;
if (amount != 0) return "can't make the last Rs " + amount;
n500 -= a; n200 -= b; n100 -= c;
return "500x" + a + " 200x" + b + " 100x" + c;
}
public static void main(String[] args) {
System.out.println(dispense(2600));
System.out.println(dispense(650));
// a new 2000 note? edit dispense(), add n2000, a fourth line, a new return...
}
}
Real output:
500x4 200x3 100x0
can't make the last Rs 50
It works, but a new note size (or an ATM with different cassettes) means editing this method every time.
The fix: the Chain of Responsibility pattern (episode 39). A chain of handlers: each handler object has a link to the next one. A request goes to the first handler; each handler does the part it can and passes the rest along the chain. Here each link is one note size.
import java.util.*;
class NoteHandler { // one link in the chain: one note size
final int note; int count; NoteHandler next;
NoteHandler(int note, int count) { this.note = note; this.count = count; }
NoteHandler then(NoteHandler n) { next = n; return n; }
void plan(int amount, Map<Integer, Integer> out) { // take what I can, pass the rest on
int n = Math.min(amount / note, count);
if (n > 0) out.put(note, n);
int rest = amount - n * note;
if (rest == 0) return;
if (next == null) throw new IllegalArgumentException("can't make the last Rs " + rest);
next.plan(rest, out); } }
class CashDispenser {
final NoteHandler first = new NoteHandler(500, 4);
{ first.then(new NoteHandler(200, 5)).then(new NoteHandler(100, 2)); }
Map<Integer, Integer> dispense(int amount) {
Map<Integer, Integer> out = new TreeMap<>(Comparator.reverseOrder());
first.plan(amount, out); // throws BEFORE any note moves
for (NoteHandler h = first; h != null; h = h.next) h.count -= out.getOrDefault(h.note, 0);
return out; }
public String toString() { String s = "left:";
for (NoteHandler h = first; h != null; h = h.next) s += " " + h.note + "x" + h.count;
return s; } }
public class Main { public static void main(String[] args) {
CashDispenser d = new CashDispenser();
for (int amt : List.of(2600, 650, 600, 600)) { String r;
try { r = "" + d.dispense(amt); } catch (IllegalArgumentException e) { r = e.getMessage(); }
System.out.println("Rs " + amt + " -> " + r + " " + d); } }}
Real output:
Rs 2600 -> {500=4, 200=3} left: 500x0 200x2 100x2
Rs 650 -> can't make the last Rs 50 left: 500x0 200x2 100x2
Rs 600 -> {200=2, 100=2} left: 500x0 200x0 100x0
Rs 600 -> can't make the last Rs 600 left: 500x0 200x0 100x0
- Rs 2600 → four 500s and three 200s.
- Rs 650 →
can't make the last Rs 50, and the box is untouched:planthrows before any count changes. - Rs 600 → two 200s and two 100s. Then Rs 600 again → empty box.
Plan first, then count out. Planning and removing notes are separate steps, so a failed plan never loses notes. A real ATM should also reject amounts that aren't a multiple of 100 straight away (the mini project does).
A new note size is just one more link (practice 4):
first = new NoteHandler(2000, 2);
first.then(new NoteHandler(500, 4)).then(new NoteHandler(200, 5)).then(new NoteHandler(100, 2));
Real output with requests 4600 and 2600:
Rs 4600 -> {2000=2, 500=1, 100=1} left: 2000x0 500x3 200x5 100x1
Rs 2600 -> {500=3, 200=5, 100=1} left: 2000x0 500x0 200x0 100x0
7. Debit, then a jam: half a transaction
A debit takes money out of an account; a credit puts money in. A withdrawal has two steps: debit the account, then dispense the notes. A jam (a note stuck in the rollers) can make step 2 fail.
class Dispenser { boolean jammed;
void give(int amt) {
if (jammed) throw new IllegalStateException("dispenser jammed");
System.out.println("cash out: Rs " + amt); } }
class ATM { int balance = 5000; final Dispenser cash = new Dispenser();
void withdraw(int amt) {
balance -= amt; // step 1: take the money from the account
cash.give(amt); // step 2: give the notes... and hope
System.out.println("done, balance Rs " + balance); } }
public class Main {
public static void main(String[] args) {
ATM atm = new ATM();
atm.withdraw(1000);
atm.cash.jammed = true; // a note gets stuck in the rollers
try { atm.withdraw(2000); }
catch (IllegalStateException e) { System.out.println(e.getMessage()); }
System.out.println("no cash came out, but balance Rs " + atm.balance);
}
}
Real output:
cash out: Rs 1000
done, balance Rs 4000
dispenser jammed
no cash came out, but balance Rs 2000
Step 1 happened, step 2 failed, and nobody undid step 1: Rs 2000 left the account and never reached the customer.
8. Transaction types and transaction rollback
Atomic means all or nothing: a transaction either happens completely, or as if it never happened. Transaction rollback means undoing the steps already done when a later step fails. Here: if dispensing fails after the debit, credit the same amount back. Failure handling means deciding, for every way something can go wrong, what the system does and what it tells the user.
The three transaction types are records behind a sealed interface (episode 8): sealed ... permits Withdraw, Deposit, BalanceEnquiry means only these three types may implement it, so a switch over a Transaction covers every case and the compiler knows nothing is missing (pattern matching for switch, episode 9).
import java.util.*;
sealed interface Transaction permits Withdraw, Deposit, BalanceEnquiry {}
record Withdraw(int amount) implements Transaction {}
record Deposit(int amount) implements Transaction {}
record BalanceEnquiry() implements Transaction {}
class Dispenser { boolean jammed;
void give(int amt) { if (jammed) throw new IllegalStateException("dispenser jammed");
System.out.println(" cash out: Rs " + amt); } }
class ATM { int balance = 5000; final Dispenser cash = new Dispenser();
String run(Transaction t) {
switch (t) {
case BalanceEnquiry b -> { return "balance Rs " + balance; }
case Deposit d -> { balance += d.amount(); return "deposited, balance Rs " + balance; }
case Withdraw w -> {
if (w.amount() > balance) return "insufficient funds, balance Rs " + balance;
balance -= w.amount(); // step 1: debit
try { cash.give(w.amount()); } // step 2: cash
catch (IllegalStateException e) {
balance += w.amount(); // ROLLBACK step 1
return e.getMessage() + ": debit reversed, balance Rs " + balance; }
return "done, balance Rs " + balance; } } } }
public class Main { public static void main(String[] args) {
ATM atm = new ATM(); atm.cash.jammed = true;
System.out.println(atm.run(new Withdraw(2000))); // jammed
atm.cash.jammed = false;
for (Transaction t : List.of(new Withdraw(2000), new Deposit(1000),
new Withdraw(9000), new BalanceEnquiry()))
System.out.println(t + " -> " + atm.run(t)); }}
Real output:
dispenser jammed: debit reversed, balance Rs 5000
cash out: Rs 2000
Withdraw[amount=2000] -> done, balance Rs 3000
Deposit[amount=1000] -> deposited, balance Rs 4000
Withdraw[amount=9000] -> insufficient funds, balance Rs 4000
BalanceEnquiry[] -> balance Rs 4000
The jammed withdrawal was reversed (balance back to Rs 5000). Then a normal withdrawal, a deposit, an over-limit withdrawal refused with insufficient funds, and a balance enquiry. Every rupee is accounted for.
9. Every way an ATM can fail
| Failure | When | What the ATM does | What the customer sees |
|---|---|---|---|
| Wrong PIN | Before anything | Try again; the 3rd blocks | "wrong PIN, try again" / "card blocked and kept" |
| Insufficient funds | Before the debit | Refuse | "insufficient funds" |
| Bad amount (650) | Before the debit | Refuse | "amount must be a multiple of 100" |
| Notes can't make it | Before the debit | Refuse (plan failed, nothing moved) | "can't make the last Rs 100" |
| Dispenser jam | After the debit | Roll back the debit | "dispenser jammed: debit reversed" |
| Bank unreachable | Before the debit | Refuse; nothing moves | "service unavailable" |
| Customer walks away | Any time | Timeout ends the session, back to Idle | — |
One rule covers them all: before the debit, refuse; after the debit, roll back.
10. The class diagram
ATM (the context)
├─has──▶ State ── Idle · HasCard · Authenticated (insert / pin / withdraw / eject)
├─uses─▶ Bank ── authenticate(card, PIN) → OK · WRONG · BLOCKED
│ └─has──▶ Account (balance) Card ── number → Account
├─has──▶ CashDispenser ── NoteHandler 500 → 200 → 100 (Chain of Responsibility)
└─runs─▶ Transaction ── Withdraw · Deposit · BalanceEnquiry (sealed)
withdraw: authenticated? → enough balance? → notes possible? → debit → dispense
dispense fails after the debit → ROLLBACK: credit it back, tell the customer
11. Interview follow-ups
| Follow-up | Answer |
|---|---|
| Transfer money | A fourth Transaction: debit one account, credit another, with the same rollback (practice 1) |
| Daily withdrawal limit | The bank tracks withdrawnToday and refuses over the limit (practice 2) |
| Two ATMs, one joint account | Lock the account during check-and-debit (synchronized, episode 46) so two withdrawals can't both pass the balance check |
| Mini statement | Keep a list of past transactions per account |
| Bank goes offline halfway | Retry, or reverse later; give each transaction a unique id so a retry is never applied twice (idempotent) |
| Refill cash | A Maintenance state for the operator |
12. Common mistakes
| Mistake | What you see (real) | Why | Fix |
|---|---|---|---|
| Boolean flags for the state | wrong PIN then take Rs 2000, balance Rs 3000 |
A method forgot a flag | State classes |
| The ATM stores and compares PINs | The secret sits in every machine | Wrong owner | Bank.authenticate |
| No limit on PIN tries | Guessing forever | No counter | 3 fails → BLOCKED |
| Removing notes while planning | Notes lost on a failed amount | Plan and act mixed | Plan, then count out |
| Debit, then dispense, no catch | no cash came out, but balance Rs 2000 |
Half a transaction | Roll back the debit |
switch on a non-sealed type with no default |
error: the switch statement does not cover all possible input values |
Compiler can't see every type | sealed ... permits, or a default |
Mini project: the complete ATM
All of today's parts in one program: Account with debit/credit, Card, Bank with authentication and blocking, the note chain, sealed transactions, the three states, checks before the debit and rollback after it.
import java.util.*;
// ---------- Bank side ----------
class Account {
final String id; private int balance;
Account(String id, int balance) { this.id = id; this.balance = balance; }
int balance() { return balance; }
void debit(int amt) {
if (amt > balance) throw new IllegalArgumentException("insufficient funds");
balance -= amt; }
void credit(int amt) { balance += amt; }
}
record Card(String number) {}
enum PinResult { OK, WRONG, BLOCKED }
class Bank {
private final Map<String, Integer> pins = new HashMap<>(), fails = new HashMap<>();
private final Map<String, Account> accounts = new HashMap<>();
void issue(Card c, int pin, Account a) { pins.put(c.number(), pin); accounts.put(c.number(), a); }
PinResult authenticate(Card c, int pin) {
String n = c.number();
if (fails.getOrDefault(n, 0) >= 3) return PinResult.BLOCKED;
if (pins.get(n) == pin) { fails.remove(n); return PinResult.OK; }
return fails.merge(n, 1, Integer::sum) >= 3 ? PinResult.BLOCKED : PinResult.WRONG;
}
Account accountOf(Card c) { return accounts.get(c.number()); }
}
// ---------- Cash dispenser: Chain of Responsibility ----------
class NoteHandler {
final int note; int count; NoteHandler next;
NoteHandler(int note, int count) { this.note = note; this.count = count; }
NoteHandler then(NoteHandler n) { next = n; return n; }
void plan(int amount, Map<Integer, Integer> out) {
int n = Math.min(amount / note, count);
if (n > 0) out.put(note, n);
int rest = amount - n * note;
if (rest == 0) return;
if (next == null) throw new IllegalArgumentException("can't make the last Rs " + rest);
next.plan(rest, out);
}
}
class CashDispenser {
final NoteHandler first; boolean jammed;
CashDispenser(int n500, int n200, int n100) {
first = new NoteHandler(500, n500);
first.then(new NoteHandler(200, n200)).then(new NoteHandler(100, n100));
}
Map<Integer, Integer> plan(int amount) { // throws if impossible; moves nothing
if (amount <= 0 || amount % 100 != 0) throw new IllegalArgumentException("amount must be a multiple of 100");
Map<Integer, Integer> out = new TreeMap<>(Comparator.reverseOrder());
first.plan(amount, out);
return out;
}
void dispense(Map<Integer, Integer> plan) {
if (jammed) throw new IllegalStateException("dispenser jammed");
for (NoteHandler h = first; h != null; h = h.next) h.count -= plan.getOrDefault(h.note, 0);
}
}
// ---------- Transactions ----------
sealed interface Transaction permits Withdraw, Deposit, BalanceEnquiry {}
record Withdraw(int amount) implements Transaction {}
record Deposit(int amount) implements Transaction {}
record BalanceEnquiry() implements Transaction {}
// ---------- ATM and its states ----------
interface State {
default void insert(Card c) { say("card already inside"); }
default void pin(int p) { say("insert card first"); }
default void run(Transaction t) { say("not allowed now"); }
default void eject() { say("no card to eject"); }
default void say(String s) { System.out.println(getClass().getSimpleName() + ": " + s); }
}
class ATM {
final Bank bank; final CashDispenser cash; State state = new Idle(this); Card card; Account account;
ATM(Bank bank, CashDispenser cash) { this.bank = bank; this.cash = cash; }
void insert(Card c) { state.insert(c); } void pin(int p) { state.pin(p); }
void run(Transaction t) { state.run(t); } void eject() { state.eject(); }
}
record Idle(ATM atm) implements State {
public void insert(Card c) { atm.card = c; atm.state = new HasCard(atm); say("card in, enter PIN"); }
}
record HasCard(ATM atm) implements State {
public void pin(int p) {
switch (atm.bank.authenticate(atm.card, p)) {
case OK -> { atm.account = atm.bank.accountOf(atm.card); atm.state = new Authenticated(atm); say("PIN ok"); }
case WRONG -> say("wrong PIN, try again");
case BLOCKED -> { atm.card = null; atm.state = new Idle(atm); say("card blocked and kept"); }
}
}
public void eject() { atm.card = null; atm.state = new Idle(atm); say("card out"); }
}
record Authenticated(ATM atm) implements State {
public void run(Transaction t) {
Account a = atm.account;
switch (t) {
case BalanceEnquiry b -> say("balance Rs " + a.balance());
case Deposit d -> { a.credit(d.amount()); say("deposited Rs " + d.amount() + ", balance Rs " + a.balance()); }
case Withdraw w -> withdraw(a, w.amount());
}
}
private void withdraw(Account a, int amt) {
Map<Integer, Integer> plan;
try {
if (amt > a.balance()) throw new IllegalArgumentException("insufficient funds");
plan = atm.cash.plan(amt); // checks BEFORE the debit: just refuse
} catch (IllegalArgumentException e) { say("refused: " + e.getMessage()); return; }
a.debit(amt); // step 1
try { atm.cash.dispense(plan); say("take Rs " + amt + " as " + plan + ", balance Rs " + a.balance()); }
catch (IllegalStateException e) { a.credit(amt); say(e.getMessage() + ": debit reversed, balance Rs " + a.balance()); }
}
public void eject() { atm.card = null; atm.account = null; atm.state = new Idle(atm); say("card out, thank you"); }
}
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();
Card asha = new Card("4111"), thief = new Card("4111");
bank.issue(asha, 4321, new Account("SB-001", 5000));
ATM atm = new ATM(bank, new CashDispenser(4, 5, 2));
atm.run(new BalanceEnquiry()); // no card yet
atm.insert(asha); atm.pin(1111); atm.pin(4321);
atm.run(new BalanceEnquiry());
atm.run(new Withdraw(2600));
atm.run(new Withdraw(650));
atm.run(new Withdraw(9000));
atm.run(new Deposit(1000));
atm.cash.jammed = true; atm.run(new Withdraw(500)); atm.cash.jammed = false;
atm.eject();
atm.insert(thief); atm.pin(1111); atm.pin(2222); atm.pin(3333);
atm.run(new Withdraw(500));
}
}
Real output:
Idle: not allowed now
Idle: card in, enter PIN
HasCard: wrong PIN, try again
HasCard: PIN ok
Authenticated: balance Rs 5000
Authenticated: take Rs 2600 as {500=4, 200=3}, balance Rs 2400
Authenticated: refused: amount must be a multiple of 100
Authenticated: refused: insufficient funds
Authenticated: deposited Rs 1000, balance Rs 3400
Authenticated: dispenser jammed: debit reversed, balance Rs 3400
Authenticated: card out, thank you
Idle: card in, enter PIN
HasCard: wrong PIN, try again
HasCard: wrong PIN, try again
HasCard: card blocked and kept
Idle: not allowed now
Practice
1. Add a Transfer(to, amount) transaction that debits one account and credits another, and rolls back if the credit fails (for example, the target account is closed).
2. Add a daily withdrawal limit of Rs 10,000.
3. Reject amounts that are not a multiple of 100 before anything else.
Answer (1, 2 and 3 together)
import java.util.*;
class Account {
final String id; int balance, withdrawnToday; static final int DAILY_LIMIT = 10_000;
Account(String id, int balance) { this.id = id; this.balance = balance; }
}
sealed interface Transaction permits Withdraw, Transfer {}
record Withdraw(int amount) implements Transaction {}
record Transfer(Account to, int amount) implements Transaction {}
class Bank {
String run(Account from, Transaction t) {
switch (t) {
case Withdraw w -> {
if (w.amount() % 100 != 0) return "refused: multiples of 100 only";
if (from.withdrawnToday + w.amount() > Account.DAILY_LIMIT) return "refused: daily limit Rs " + Account.DAILY_LIMIT;
if (w.amount() > from.balance) return "refused: insufficient funds";
from.balance -= w.amount(); from.withdrawnToday += w.amount();
return "withdrew Rs " + w.amount() + ", balance Rs " + from.balance;
}
case Transfer tr -> {
if (tr.amount() > from.balance) return "refused: insufficient funds";
from.balance -= tr.amount(); // step 1: debit one account
try {
if (tr.to().id.startsWith("CLOSED")) throw new IllegalStateException("target account closed");
tr.to().balance += tr.amount(); // step 2: credit the other
} catch (IllegalStateException e) {
from.balance += tr.amount(); // rollback step 1
return e.getMessage() + ": debit reversed, balance Rs " + from.balance;
}
return "sent Rs " + tr.amount() + " to " + tr.to().id + ", balance Rs " + from.balance;
}
}
}
}
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();
Account asha = new Account("SB-001", 20_000), ravi = new Account("SB-002", 0), old = new Account("CLOSED-9", 0);
System.out.println(bank.run(asha, new Withdraw(650)));
System.out.println(bank.run(asha, new Withdraw(8000)));
System.out.println(bank.run(asha, new Withdraw(3000)));
System.out.println(bank.run(asha, new Transfer(ravi, 2000)) + "; ravi has Rs " + ravi.balance);
System.out.println(bank.run(asha, new Transfer(old, 1000)));
}
}
Real output:
refused: multiples of 100 only
withdrew Rs 8000, balance Rs 12000
refused: daily limit Rs 10000
sent Rs 2000 to SB-002, balance Rs 10000; ravi has Rs 2000
target account closed: debit reversed, balance Rs 10000
4. Add a Rs 2000 link at the front of the chain. Which notes do 4600 and then 2600 give?
Answer
One new line builds the chain (section 6). Real output: Rs 4600 -> {2000=2, 500=1, 100=1} left: 2000x0 500x3 200x5 100x1 and then Rs 2600 -> {500=3, 200=5, 100=1} left: 2000x0 500x0 200x0 100x0. Nothing else in CashDispenser changed: that's the point of the chain.
5. Why must Bank.authenticate, not the ATM, count failed PIN tries?
Answer
Because the count belongs to the card, not the machine. If each ATM counted, a thief could try 2 PINs at each of many ATMs forever. The bank sees every try from every ATM.
Quick quiz
Box: 500 × 1, 200 × 3, 100 × 0. Request: Rs 600. The chain 500 → 200 → 100, each link taking min(fit, have). What happens? (a) {500=1, 100=1} (b) {200=3} (c) can't make the last Rs 100 (d) {500=1}
Answer
(c). Real output of the chain with that box:
Rs 600 -> can't make the last Rs 100 left: 500x1 200x3 100x0
The 500 link takes its one note, leaving Rs 100; no 200 fits into 100 and there are no 100s. But 200 × 3 = 600 was possible: greedy missed it (like the vending machine's change). Because we plan first, no note moved. The fix is to try other mixes (backtracking or dynamic programming) when greedy fails.
Interview questions
- Which patterns fit an ATM? State (Idle / HasCard / Authenticated), Chain of Responsibility (note denominations), and sealed types or Command for transactions.
- Why not boolean flags? Flags combine into impossible states and every method must check every flag; one forgotten check gave cash to a wrong PIN.
- Who verifies the PIN? The bank. The ATM sends the card and PIN and gets
OK/WRONG/BLOCKED. - How do you block a card? The bank counts failures per card; at 3 it answers
BLOCKEDand the ATM keeps the card. A correct PIN resets the count. - How does the dispenser choose notes? A chain of note handlers, biggest first, each taking
min(amount / note, count)and passing the rest on; plan first, remove notes only if the plan works. - What is a transaction rollback? Undoing completed steps when a later step fails: debit done, dispense failed → credit back.
- Check before or after the debit? Every check you can do (balance, amount, notes) comes before the debit; only failures you can't foresee (a jam) need a rollback.
- How do you handle two withdrawals on one account at once? Make check-and-debit atomic with a lock on the account.
- What if the bank is unreachable after the cash came out? Record the transaction with a unique id and reconcile later; ids make retries idempotent.
- How would you add a new transaction type? Add a record to the sealed interface's
permitslist; the compiler then flags everyswitchthat doesn't handle it.
Glossary
| Term | Meaning, with an example |
|---|---|
| ATM | Automated teller machine: gives and takes cash without a person at a counter |
| ATM requirements | Card → PIN → transaction; bank checks PIN; 3 fails block; withdraw up to the balance in available notes; never debit without dispensing |
| Requirement | Something the system must do, agreed before coding |
| Entity | A thing in the problem with its own data and rules: Card, Account |
| Card | A key that says which account: Card("4111"). It holds no money |
| Account | Where money lives at the bank: Account("SB-001", 5000) |
| Bank | Knows PINs and accounts; answers the ATM's questions |
| Balance | How much money is in an account right now |
| PIN | Personal identification number, a short secret like 4321 |
| Authentication | Proving who you are; at an ATM, typing the card's PIN |
| Authentication with PIN | The bank compares the PIN and answers OK, WRONG or BLOCKED |
| Card blocking | After 3 wrong PINs the bank refuses that card, even with the right PIN |
| Boolean flag | A true/false variable remembering one fact: pinVerified |
| ATM states | Idle, HasCard, Authenticated: each allows different buttons |
| State pattern | Each state is a class behind one interface; the context delegates to the current one (episode 37) |
| Context | The object that holds the current state and passes calls to it: ATM |
| Delegate | Pass a call on to another object: void pin(int p) { state.pin(p); } |
| Default method | An interface method with a body: default void pin(int p) { say("insert card first"); } |
| Record | A small class with fixed fields: record Withdraw(int amount) |
| Transaction | One complete job: withdraw, deposit, or balance enquiry |
| Transaction types: withdraw, deposit, balance | Withdraw takes cash out, deposit puts cash in, balance enquiry only shows the balance |
| Sealed interface | Only the listed types may implement it: sealed interface Transaction permits Withdraw, Deposit, BalanceEnquiry |
| Pattern matching for switch | case Withdraw w -> ... checks the type and names it in one step |
| Cash dispenser | The box of notes inside the ATM and the rollers that push them out |
| Denomination | The face value of a note: 500, 200, 100 |
| Greedy | Take the biggest piece first, as many as fit, then the next |
| Chain of Responsibility | A chain of handlers, each with a link to the next; each handles what it can and passes the rest on (episode 39) |
| Chain of Responsibility for note denominations | One NoteHandler per note size: 500 → 200 → 100 |
| Debit | Money taken out of an account |
| Credit | Money put into an account |
| Jam | A note stuck in the rollers: the dispenser can't give cash |
| Atomic | All or nothing |
| Transaction rollback | Undoing finished steps when a later one fails: debit done, dispense failed → credit back |
| Failure handling | Deciding what the system does and says for every way things can go wrong |
| Insufficient funds | The amount asked is more than the balance |
| Idempotent | Doing it twice has the same effect as once; a transaction id makes retries safe |
| Timeout | Ending a session automatically after no activity |
Summary
- Requirements: card → PIN → transaction; the bank checks the PIN and blocks after 3; withdraw up to the balance in notes the machine has; never debit without dispensing.
- Boolean flags let a wrong PIN withdraw:
wrong PIN, thentake Rs 2000. - ATM states
Idle → HasCard → Authenticatedwith the State pattern; authentication by the bank:OK,WRONG,BLOCKED. - Cash dispenser as a Chain of Responsibility: one link per denomination, plan first, then count out.
- Transaction types
Withdraw,Deposit,BalanceEnquiryas a sealed interface. - Before the debit, refuse; after the debit, roll back (
dispenser jammed: debit reversed).
Next episode: Design an LRU cache: eviction, a HashMap plus a doubly linked list, O(1) get and put.