LLD

Full Designs

Vending Machine

Three states and a balance are enough to teach the State pattern. An interview pushes further. We build a machine that stays correct when it runs short of change, which it decides before the spiral turns, when a card declines or never answers, when a spiral jams, and when an operator opens the door.

The State pattern page's three states and a balance teach the pattern. An interview pushes further. A design that stops at those three states assumes the machine always has coins for change and that every product drops, and those are the parts that make a real machine hard.

The interviewer is checking the money. A customer's coins, a card hold and a product in a spiral must stay in step, and each can fail on its own. The tubes can run short of coins for change. The card network can say no, or say nothing. A spiral can turn and drop nothing. An operator can open the door at any time of day. For each of these, the design has to say who ends up with the money.

This page uses the pattern and does not teach it again. It follows a 45 minute interview: we ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

A vending machine at a glance
A customer puts cash in, and it waits in escrow (1). The customer picks a slot (2), and the machine plans the change from the tubes and the customer's own coins before anything moves. A card customer gets a hold from the processor instead, captured only after the drop (3). The dispenser turns the spiral, and the drop sensor says whether a product fell (4). Only then is the money kept, and any change drops into the tray (5). The operator's service button opens a ServiceSession (6), and customers get OUT_OF_SERVICE until it closes.A customer puts cash in, and it waits in escrow (1). The customer picks a slot (2), and the machine plans the change from the tubes and the customer's own coins before anything moves. A card customer gets a hold from the processor instead, captured only after the drop (3). The dispenser turns the spiral, and the drop sensor says whether a product fell (4). Only then is the money kept, and any change drops into the tray (5). The operator's service button opens a ServiceSession (6), and customers get OUT_OF_SERVICE until it closes.
Nothing is kept until the product drops. A customer puts cash in, and it waits in escrow (1). The customer picks a slot (2), and the machine plans the change from the tubes and the customer's own coins before anything moves. A card customer gets a hold from the processor instead, captured only after the drop (3). The dispenser turns the spiral, and the drop sensor says whether a product fell (4). Only then is the money kept, and any change drops into the tray (5). The operator's service button opens a ServiceSession (6), and customers get OUT_OF_SERVICE until it closes.

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
What money does it take?Nickels, dimes, quarters and $1 coins, and $1 and $5 notes. Change comes only in nickels, dimes and quartersA Cash enum, and three change tubes
Where does inserted money wait?In an escrow, untouched, until a product dropsThe machine keeps the coins themselves, not a balance
Is there always change?No. The tubes hold what the operator loaded and what customers paidA change plan before the spiral turns, and a refusal that keeps the money
Can customers pay by card?Yes, by tapping. The network can decline or not answerA PaymentProcessor with a hold, a capture and a void
How does the machine know a product fell?A sensor under the spirals sees itDispenser answers DROPPED or JAMMED, and a jam blocks the slot
Who restocks, and when?An operator, with the door open. Customers are turned away meanwhileA ServiceSession and a maintenance state
Who sets prices?The operator, per slot, in steps of 5 cents up to $10The price lives on the slot, and a sale keeps the price it started with
What are the limits?Up to $20 in escrow, up to 20 items a spiral, 60 coins a tubeA check at each limit
What calls the machine?The keypad, the coin slot, the card reader, the door and a timer, each on its own threadOne lock, and a state that guards the slow calls

The third question matters most. If the machine always has change, the customer's money can be a number, and a sale is a subtraction. If it does not, the machine must know which coins it holds, and it must find out before the product drops whether it can pay the change. A machine that finds out after has already sold the product.

Requirements

Functional:

  1. With the door open, an operator loads slots with a product, a price and a count, adds coins to the change tubes, clears jams and empties the cash box. While the door is open, customers are turned away and any cash they insert is handed back.
  2. A customer puts in up to $20 in cash and picks a slot. They get the product and exact change, or a refusal that keeps their money in escrow.
  3. The machine decides whether it can give change before the spiral turns. If the tubes and the customer's coins together cannot make it, the sale is refused.
  4. Cancel returns the very coins and notes that went in, at any time before a sale starts.
  5. A customer can tap a card instead. The card is charged only if the product drops. A decline or no answer sells nothing, and any hold is voided, retried until the network confirms.
  6. If nothing drops, the customer pays nothing, and the slot is blocked until an operator clears it.
  7. Two presses at the same moment never drop two products for one payment.

Out of scope: prices sent from the office, a coin tray that jams, paying with cash and a card together, age checks, alerts for low stock, and surviving a restart. We come back to these at the end, because each is a likely follow-up.

Everything lives in memory, as is normal for a low-level design interview. The card network, the motors and the coin tray are interfaces, and the project has fakes for them.

What the code itself must handle:

  • Several callers at once. The keypad, the card reader and the operator's door all call the machine.
  • Calls that fail or hang. A card network call has three outcomes, not two, and a motor can stall.
  • Money that adds up. Every amount is a whole number of cents in a long, never a double.
  • Testable hardware. Everything physical sits behind an interface.

Finding the classes

Picking the nouns out of the requirements gives a first list. Most become classes, records, enums or interfaces. A few are dropped, and dropping them is part of the design.

From nouns to classes
The machine, the operator's open door and the change rule become classes. A slot, a sale and any count of coins become records, and a coin or note becomes the Cash enum. The machine's situations, the card network, the motors and the coin tray become interfaces. Six nouns are dropped. A balance is what the coins in escrow already say. A product is a name on its slot. The customer and the keypad are callers of VendingMachine, and the screen shows Reply.screen. The slots are the inventory.The machine, the operator's open door and the change rule become classes. A slot, a sale and any count of coins become records, and a coin or note becomes the Cash enum. The machine's situations, the card network, the motors and the coin tray become interfaces. Six nouns are dropped. A balance is what the coins in escrow already say. A product is a name on its slot. The customer and the keypad are callers of VendingMachine, and the screen shows Reply.screen. The slots are the inventory.
The coins stay. The balance goes. The machine, the operator's open door and the change rule become classes. A slot, a sale and any count of coins become records, and a coin or note becomes the Cash enum. The machine's situations, the card network, the motors and the coin tray become interfaces. Six nouns are dropped. A balance is what the coins in escrow already say. A product is a name on its slot. The customer and the keypad are callers of VendingMachine, and the screen shows Reply.screen. The slots are the inventory.

The noun that needs the most thought is balance, because the State pattern page keeps one, and it is the first field most designs write.

Decision

Keep a balance, or keep the coins?

A balance in cents, as the State pattern page does

A balance makes every check one comparison. The State pattern page keeps one because it assumes the machine always has change, and says so. Here it does not. A cancel must then pay the balance back from the tubes, which may not hold the right coins. A customer who put in a $5 note could get twenty quarters back, or nothing.

The coins themselves, in an escrow CashCountOur pick

The escrow is a count of each coin and note the customer put in. Cancel hands back exactly that, whatever the tubes hold. The change plan can also use the customer's own coins, which a balance hides. The cost is a small record with plus and minus in place of a number.

Data or behaviour?

Some classes only carry values that never change: a slot's contents, a sale in progress, a count of coins, the machine's reply. In Java these are records. A record's fields are fixed when it is created, and it gets equals, hashCode and toString without writing them. A slot's stock does change, but the machine replaces the Slot record rather than editing it. A change is either all made or not made at all.

money/CashCount.javalines 9–27 of 99
/** How many of each coin and note: a customer's escrow, the change tubes, the cash box or some change. */public record CashCount(Map<Cash, Integer> counts) {    public static final CashCount NONE = new CashCount(Map.of());     public CashCount {        Objects.requireNonNull(counts, "counts");        EnumMap<Cash, Integer> copy = new EnumMap<>(Cash.class);        for (Map.Entry<Cash, Integer> entry : counts.entrySet()) {            Cash cash = Objects.requireNonNull(entry.getKey(), "cash");            int count = Objects.requireNonNull(entry.getValue(), "count");            if (count < 0) {                throw new IllegalArgumentException("A count cannot be negative: " + count + " x " + cash);            }            if (count > 0) {                copy.put(cash, count);            }        }        counts = Collections.unmodifiableMap(copy);    }

CashCount maps each Cash value to a count. The constructor refuses a negative count, drops the zeros and keeps an unmodifiable copy, so two counts holding the same coins are always equal. The escrow, the tubes, the cash box and a customer's change are all CashCounts. plus adds with Math.addExact, and totalCents multiplies with Math.multiplyExact, so an overflow throws instead of wrapping round.

The class diagram

The classes and how they connect
VendingMachine holds the slots, the escrow, the tubes, the cash box, the current MachineState, the open ServiceSession and the payments still to settle, all under one lock. It reaches the card network, the motors and the coin tray through PaymentProcessor, Dispenser and CoinReturn. Four state classes implement MachineState. HasMoneyState calls the static ChangePlanner. Methods marked ~ are package-private. The records and enums along the bottom are the values the classes pass around. The exception class is not drawn.VendingMachine holds the slots, the escrow, the tubes, the cash box, the current MachineState, the open ServiceSession and the payments still to settle, all under one lock. It reaches the card network, the motors and the coin tray through PaymentProcessor, Dispenser and CoinReturn. Four state classes implement MachineState. HasMoneyState calls the static ChangePlanner. Methods marked ~ are package-private. The records and enums along the bottom are the values the classes pass around. The exception class is not drawn.
VendingMachine coordinates. Four interfaces stand for its states and for everything outside the code. VendingMachine holds the slots, the escrow, the tubes, the cash box, the current MachineState, the open ServiceSession and the payments still to settle, all under one lock. It reaches the card network, the motors and the coin tray through PaymentProcessor, Dispenser and CoinReturn. Four state classes implement MachineState. HasMoneyState calls the static ChangePlanner. Methods marked ~ are package-private. The records and enums along the bottom are the values the classes pass around. The exception class is not drawn.

The classes fall into three groups:

  • Data: the records Slot, Sale, CashCount, Reply and Step, and the enums Cash, Outcome, AuthResult and VendResult.
  • The core: VendingMachine, its four states, ServiceSession and ChangePlanner.
  • Outside systems: PaymentProcessor, Dispenser and CoinReturn, all interfaces. The project's FakeProcessor and FakeDispenser stand in for them.

Customers never see an exception for something a person can do wrong. Every customer action returns a Reply: an Outcome, a line for the screen, and any cash that dropped into the tray. An operator's mistake, such as a price of $1.23, throws from ServiceSession, and the service panel shows the message. A null argument is a bug in the calling code, and it throws too.

Building it

Slots and prices

A slot is one spiral. It holds a product name, a price, a count and a jammed flag:

slot/Slot.javalines 14–47 of 80
public record Slot(String code, String product, long priceCents, int count, int capacity, boolean jammed) {    public static final Pattern CODE = Pattern.compile("[A-F][1-9]");    public static final long MAX_PRICE_CENTS = 1_000;     public Slot {        Objects.requireNonNull(code, "code");        Objects.requireNonNull(product, "product");        if (!CODE.matcher(code).matches()) {            throw new IllegalArgumentException("A slot code is a letter A to F and a digit 1 to 9, not " + code);        }        if (product.isBlank() || product.length() > 30) {            throw new IllegalArgumentException("A product name is 1 to 30 characters: '" + product + "'");        }        if (priceCents <= 0 || priceCents > MAX_PRICE_CENTS || priceCents % 5 != 0) {            throw new IllegalArgumentException("A price is a multiple of 5 cents, up to $10.00, not " + priceCents);        }        if (capacity <= 0) {            throw new IllegalArgumentException("A spiral holds at least one item, not " + capacity);        }        if (count < 0 || count > capacity) {            throw new IllegalArgumentException("Slot " + code + " holds 0 to " + capacity + " items, not " + count);        }    }     /** Why this slot cannot sell right now, or empty if it can. */    public Optional<String> whyNotForSale() {        if (jammed) {            return Optional.of(code + " is out of order");        }        if (count == 0) {            return Optional.of(product + " is sold out");        }        return Optional.empty();    }

The constructor checks every limit. A price must be a multiple of 5 cents (line 27), because the smallest coin the machine can give back is a nickel. A price of $1.23 would leave 2 cents of change that no coin can pay. whyNotForSale gives the reason a slot cannot sell, or nothing if it can. A jammed slot is out of order even if it still holds items, and an empty one is sold out.

The machine's states

The machine is in one of four states. Ready waits for a customer. HasMoney holds a customer's cash in escrow. Vending has a sale running: the card network is being asked, or a spiral is turning. Maintenance has the door open.

Each slot sells out on its own, so sold out is a check in whyNotForSale. A machine with every slot empty stays in Ready and answers each press with "sold out".

machine/MachineState.javalines 5–17 of 17
/** One situation the machine can be in. VendingMachine calls these with its lock held. */interface MachineState {    Reply insert(VendingMachine machine, Cash cash);     Step select(VendingMachine machine, String code);     Step tapCard(VendingMachine machine, String code, String cardToken);     Reply cancel(VendingMachine machine);     /** True if the machine is now in maintenance. */    boolean openDoor(VendingMachine machine);}

Each state answers five actions. select and tapCard return a Step, which is either an answer to show now or a sale to run. Here is the machine's side:

machine/VendingMachine.javalines 89–96 of 434
    public Reply select(String code) {        Objects.requireNonNull(code, "code");        Step step;        synchronized (lock) {            step = state.select(this, code);        }        return step.sale() == null ? handBack(step.reply()) : runSale(step.sale());    }

The state runs under the machine's lock (lines 92 to 94). If it starts a sale, the sale runs after the lock is let go (line 95). That split is why Step exists. A state must not call the card network or the motor, because the lock would then be held for seconds.

VendingState is short. It refuses everything:

machine/VendingState.javalines 6–18 of 34
/** A sale is running: the card is being asked, or the spiral is turning. */class VendingState implements MachineState {    private static final String WAIT = "Please wait, your product is on its way";     @Override    public Reply insert(VendingMachine machine, Cash cash) {        return new Reply(Outcome.WAIT, WAIT, CashCount.of(cash, 1));    }     @Override    public Step select(VendingMachine machine, String code) {        return Step.answer(Outcome.WAIT, WAIT);    }

A coin inserted mid-sale goes straight back to the tray (line 12). Cancel is refused too, so a customer cannot take the money back while the product is falling.

Decision

Is a sale in progress a state of its own?

No: run the whole sale inside select, under the lock

There are three states, and nothing can happen in the middle of a sale. But the lock is then held while the card network answers, which can take many seconds, and while the motor turns. The operator's door and every read of the machine wait behind it.

Yes: VendingState, and the lock is held only to change stateOur pick

The State pattern page says a dispensing state earns its place only if the machine can be in it when the next action arrives. Here it can, because the slow calls run without the lock and a second press can arrive meanwhile. VendingState answers that press with WAIT. The cost is a fourth state class, and a sale that ends in machine code rather than inside a state, because it ends after the lock was let go.

Change, decided before the drop

A customer in HasMoney presses a button. HasMoneyState.select runs every check before anything moves:

machine/HasMoneyState.javalines 22–45 of 63
    @Override    public Step select(VendingMachine machine, String code) {        Optional<Reply> refusal = machine.cannotSell(code);        if (refusal.isPresent()) {            return Step.answer(refusal.get());        }        Slot slot = machine.slotAt(code);        CashCount escrow = machine.escrow();        long paid = escrow.totalCents();        if (paid < slot.priceCents()) {            return Step.answer(Outcome.NOT_ENOUGH_MONEY, slot.product() + " is " + Dollars.format(slot.priceCents())                    + ". Insert " + Dollars.format(slot.priceCents() - paid) + " more");        }        long changeCents = paid - slot.priceCents();        // The customer's own coins can be part of the change.        Optional<CashCount> change = ChangePlanner.plan(changeCents, machine.tubes().plus(escrow.tubeCoins()));        if (change.isEmpty()) {            return Step.answer(Outcome.NO_CHANGE, "Exact change only: no coins for "                    + Dollars.format(changeCents) + " change. Pick another or press cancel");        }        Sale sale = Sale.cash(slot, change.get());        machine.startSale(sale);        return Step.run(sale);    }

First, the slot must be able to sell. Then the escrow must cover the price (line 31). Then comes the change. The coins on hand are the tubes plus the customer's own coins in escrow (line 37). If ChangePlanner finds no mix of coins, the answer is NO_CHANGE and the money stays in escrow (lines 38 to 41). startSale moves the machine to Vending (line 43) only after every check passes. The plan goes into the Sale, so nothing is worked out again after the drop.

Change, before the spiral turns
On the left, Meera pays a $1 note and three quarters for a $1.50 bar. The tubes hold only a dime and a nickel, which cannot make 25 cents. With her quarters, the planner finds one quarter, so the bar drops and one of her quarters comes back. On the right, Ravi pays a $5 note for $0.85 gum. The machine holds $0.90 in coins, so no mix makes $4.15. The answer is NO_CHANGE before anything moves, and cancel returns his note.On the left, Meera pays a $1 note and three quarters for a $1.50 bar. The tubes hold only a dime and a nickel, which cannot make 25 cents. With her quarters, the planner finds one quarter, so the bar drops and one of her quarters comes back. On the right, Ravi pays a $5 note for $0.85 gum. The machine holds $0.90 in coins, so no mix makes $4.15. The answer is NO_CHANGE before anything moves, and cancel returns his note.
The customer's own coins count. A refusal costs nothing. On the left, Meera pays a $1 note and three quarters for a $1.50 bar. The tubes hold only a dime and a nickel, which cannot make 25 cents. With her quarters, the planner finds one quarter, so the bar drops and one of her quarters comes back. On the right, Ravi pays a $5 note for $0.85 gum. The machine holds $0.90 in coins, so no mix makes $4.15. The answer is NO_CHANGE before anything moves, and cancel returns his note.

The planner searches, because taking the biggest coin first can fail when a tube is short. With one quarter and three dimes, 30 cents fails if the quarter goes first, and three dimes pay it. The ATM page shows the same trap with notes and explains the search. Here the search is small: at most 80 counts of quarters, and for each at most 200 counts of dimes.

money/ChangePlanner.javalines 12–36 of 37
    /**     * Tries every count of quarters, most first, and for each every count of     * dimes, most first. Nickels make up the rest. Empty if no mix works.     */    public static Optional<CashCount> plan(long amountCents, CashCount onHand) {        Objects.requireNonNull(onHand, "onHand");        if (amountCents < 0) {            throw new IllegalArgumentException("Change cannot be negative: " + amountCents);        }        long mostQuarters = Math.min(onHand.count(Cash.QUARTER), amountCents / 25);        for (long quarters = mostQuarters; quarters >= 0; quarters--) {            long afterQuarters = amountCents - quarters * 25;            long mostDimes = Math.min(onHand.count(Cash.DIME), afterQuarters / 10);            for (long dimes = mostDimes; dimes >= 0; dimes--) {                long rest = afterQuarters - dimes * 10;                if (rest % 5 == 0 && rest / 5 <= onHand.count(Cash.NICKEL)) {                    return Optional.of(new CashCount(Map.of(                            Cash.QUARTER, (int) quarters,                            Cash.DIME, (int) dimes,                            Cash.NICKEL, (int) (rest / 5))));                }            }        }        return Optional.empty();    }
Decision

When does the machine decide it can give change?

From the tubes alone, with an exact change light

The light warns customers early. But it refuses sales that the customer's own coins could pay, such as Meera's, and a light based on the tubes cannot know what the next customer will insert.

After the product drops, paying what it can

The sale never stops for change. But the customer can be short-changed for a product already in the bin, and the machine has to record a debt to someone who has walked away.

Before the spiral turns, from the tubes and the customer's coinsOur pick

A refusal costs nothing, because nothing has moved, and the customer can pick another product or cancel. The plan is fixed in the Sale, and nothing can change the tubes during Vending, because the door stays shut. The cost is one search per sale, which is small.

When the product drops, the sale is finished under the lock:

machine/VendingMachine.javalines 169–192 of 434
    private Reply runCashSale(Sale sale) {        VendResult result = vend(sale);        Reply reply;        synchronized (lock) {            reply = result == VendResult.DROPPED ? completeCashSale(sale) : jamCashSale(sale);        }        return handBack(reply);    }     /** Lock held. The product dropped, so the escrow is kept and the change planned at the start goes out. */    private Reply completeCashSale(Sale sale) {        CashCount pool = tubes.plus(escrow.tubeCoins()).minus(sale.change());        CashCount newTubes = pool.atMost(TUBE_CAPACITY);        CashCount notes = escrow.minus(escrow.tubeCoins());        CashCount newCashBox = cashBox.plus(notes).plus(pool.minus(newTubes));        Slot sold = slots.get(sale.slotCode()).withOneLess();        // Everything that can throw has run. Only now does the state change.        slots.put(sale.slotCode(), sold);        tubes = newTubes;        cashBox = newCashBox;        escrow = CashCount.NONE;        endSale(new ReadyState());        return new Reply(Outcome.VENDED, "Enjoy your " + sale.product(), sale.change());    }

The spiral turns with no lock held (line 170). Then completeCashSale works out the new tubes, the new cash box and the new slot first (lines 180 to 184). The customer's coins join the tubes, and the change comes out of them. Notes and dollar coins go to the cash box, and so does anything past a full tube of 60. Anything that can throw has run by now. The fields change only after that (lines 186 to 190). After the lock is let go, handBack drops the change into the tray.

Paying by card

A tap in Ready checks the slot, creates a Sale with a new payment key, and moves to Vending:

machine/ReadyState.javalines 31–41 of 53
    @Override    public Step tapCard(VendingMachine machine, String code, String cardToken) {        Optional<Reply> refusal = machine.cannotSell(code);        if (refusal.isPresent()) {            return Step.answer(refusal.get());        }        // A random key, so a key never repeats, even after a restart.        Sale sale = Sale.card(machine.slotAt(code), UUID.randomUUID().toString(), cardToken);        machine.startSale(sale);        return Step.run(sale);    }

The key is a random UUID (line 38). A counter such as S-41 would start again after a restart, and the network would then answer a new sale with an old sale's result. The processor's contract says what a repeated key does:

payment/PaymentProcessor.javalines 7–24 of 24
public interface PaymentProcessor {    /**     * Holds the amount on the card. Nothing is charged yet. A second call with     * the same key returns the first answer and places no second hold. After     * voidHold(key), a hold with that key is DECLINED.     */    AuthResult authorize(String paymentKey, String cardToken, long amountCents);     /** Charges the card for that key's hold. A second capture with the same key does nothing. */    void capture(String paymentKey);     /**     * Drops that key's hold. A second void does nothing. A void for a key the     * processor has not seen blocks the key, so a hold that arrives late is     * declined.     */    void voidHold(String paymentKey);}

A hold reserves the amount on the card and charges nothing. A capture charges it, and a void drops it. Each of the three is safe to send twice with the same key. A void for a key the network has not seen blocks the key, so a hold that arrives late is declined.

machine/VendingMachine.javalines 202–240 of 434
    private Reply runCardSale(Sale sale) {        String key = sale.paymentKey();        AuthResult answer;        try {            answer = Objects.requireNonNull(payments.authorize(key, sale.cardToken(), sale.priceCents()), "answer");        } catch (RuntimeException noAnswer) {            // A hold may exist, or may still arrive. Voiding the key covers both.            synchronized (lock) {                pendingVoids.add(key);                endSale(new ReadyState());            }            sendVoid(key);            return Reply.of(Outcome.NO_ANSWER, "No answer from the card network. Nothing was charged");        }        if (answer == AuthResult.DECLINED) {            synchronized (lock) {                endSale(new ReadyState());            }            return Reply.of(Outcome.DECLINED, "Card declined");        }        VendResult result = vend(sale);        if (result == VendResult.DROPPED) {            synchronized (lock) {                Slot sold = slots.get(sale.slotCode()).withOneLess();                slots.put(sale.slotCode(), sold);                pendingCaptures.add(key);                endSale(new ReadyState());            }            sendCapture(key);            return Reply.of(Outcome.VENDED, "Enjoy your " + sale.product());        }        synchronized (lock) {            slots.put(sale.slotCode(), slots.get(sale.slotCode()).jam());            pendingVoids.add(key);            endSale(new ReadyState());        }        sendVoid(key);        return Reply.of(Outcome.JAMMED, sale.slotCode() + " is out of order. Your card was not charged");    }

The hold is asked for without the lock (line 206). A decline ends the sale with nothing held (lines 216 to 220). An approval turns the spiral (line 222). If the product drops, the key goes into pendingCaptures under the lock (line 227), and the capture is sent after it (line 230). If nothing drops, the key goes into pendingVoids instead (line 235), and the void is sent (line 238).

A card sale, and every way it can end
Dev taps a card for B1 (1). tapCard creates a Sale with a random key and moves to Vending (2). The processor holds $2.35 (3). A decline ends the sale with no hold. No answer ends it too, and the same key is voided. An approval turns the spiral, and the sensor answers (4). DROPPED captures the hold. JAMMED blocks B1 and voids it. A capture or a void that gets no answer waits in pendingCaptures or pendingVoids (5), and retryPayments sends it again with the same key. A cash sale that jams keeps the coins in escrow instead.Dev taps a card for B1 (1). tapCard creates a Sale with a random key and moves to Vending (2). The processor holds $2.35 (3). A decline ends the sale with no hold. No answer ends it too, and the same key is voided. An approval turns the spiral, and the sensor answers (4). DROPPED captures the hold. JAMMED blocks B1 and voids it. A capture or a void that gets no answer waits in pendingCaptures or pendingVoids (5), and retryPayments sends it again with the same key. A cash sale that jams keeps the coins in escrow instead.
The card is charged only after the sensor sees the product. Dev taps a card for B1 (1). tapCard creates a Sale with a random key and moves to Vending (2). The processor holds $2.35 (3). A decline ends the sale with no hold. No answer ends it too, and the same key is voided. An approval turns the spiral, and the sensor answers (4). DROPPED captures the hold. JAMMED blocks B1 and voids it. A capture or a void that gets no answer waits in pendingCaptures or pendingVoids (5), and retryPayments sends it again with the same key. A cash sale that jams keeps the coins in escrow instead.
Decision

Charge the card and refund a jam, or hold, then capture?

Charge first, refund if nothing drops

There is one call on the happy path. But a jam means a charge and a refund. The customer sees both on the statement, and the refund can take days to arrive.

Hold before the spiral turns, capture after the drop, void after a jamOur pick

The money moves only after the sensor sees the product. A jam drops the hold, so the customer is never charged. The cost is a second call on every sale, and a capture that can fail after the customer already has the product. That capture waits in pendingCaptures and is sent again.

If the network does not answer, nobody knows whether a hold was placed. The machine voids the key at once (lines 208 to 213). The void covers every case: it drops a hold that exists, and it blocks one that is still on its way. If the void gets no answer as well, the key stays in pendingVoids.

Decision

The card gets no answer. Ask again, or give up the sale?

Ask again with the same key, as the ATM does

A lost reply often turns into a sale on the second try. But the customer stands at the machine through a second timeout, for one item worth a few dollars.

Give up the sale and void the keyOur pick

The customer hears "nothing was charged" within one timeout, and can tap again or pay cash. A new tap gets a new key, so it can never be confused with the first. The void with the old key makes sure no hold from the first tap survives. The cost is a lost sale whenever the network was only slow.

A timer calls retryPayments, which sends every waiting capture and void again. It is the same retry list the ATM keeps for reversals:

machine/VendingMachine.javalines 271–281 of 434
    private boolean sendCapture(String key) {        try {            payments.capture(key);        } catch (RuntimeException noAnswer) {            return false;        }        synchronized (lock) {            pendingCaptures.remove(key);        }        return true;    }

A key leaves pendingCaptures only after the processor takes the capture (lines 277 to 279). If the timer and a sale send the same void at once, the processor's promise makes the second one do nothing.

When nothing drops

The sensor can see nothing fall. The motor can also throw, or answer null, and then nobody saw a product either:

machine/VendingMachine.javalines 242–253 of 434
    private VendResult vend(Sale sale) {        synchronized (lock) {            spiralTurned = true;        }        try {            VendResult result = dispenser.vend(sale.slotCode());            return result == null ? VendResult.JAMMED : result;        } catch (RuntimeException motorFault) {            // Nobody saw a product drop, so the customer does not pay for one.            return VendResult.JAMMED;        }    }

Before the motor starts, vend notes under the lock that the spiral has turned (lines 243 to 245). The motor itself runs with no lock held. A motor that answers null or throws counts as a jam (lines 248 to 251).

A cash sale that jams blocks the slot and goes back to HasMoney with the escrow untouched:

machine/VendingMachine.javalines 194–200 of 434
    /** Lock held. Nothing dropped: the slot is blocked and the cash stays in escrow. */    private Reply jamCashSale(Sale sale) {        slots.put(sale.slotCode(), slots.get(sale.slotCode()).jam());        endSale(new HasMoneyState());        return Reply.of(Outcome.JAMMED, sale.slotCode() + " is out of order. Your "                + Dollars.format(escrow.totalCents()) + " is still in. Pick another or press cancel");    }

The customer's money never left escrow, so nothing is refunded. They can pick another product with it or press cancel. A card sale that jams voids its hold, as above.

Decision

Nothing dropped. Who keeps the money?

The machine keeps it, and an operator refunds later

The books are simple. But the customer pays for nothing, and has to find someone to ask.

Turn the spiral again

A second turn often frees the product. But if the first item was only slow, both can fall for one payment. A retry belongs inside the Dispenser, which can see the motor.

The customer pays nothing, the slot is blocked, and a silent motor counts as a jamOur pick

The customer is never charged for a product nobody saw. The slot refuses everyone until an operator counts what is left, so the next customer does not lose money to the same jam. The ATM stops and leaves the account to a person when it cannot tell how much cash came out. A vending machine risks one product at most, so here the customer gets the benefit of the doubt.

One more case remains. If something escapes the sale code, such as an Error, the machine must not stay in Vending for good:

machine/VendingMachine.javalines 156–167 of 434
    private Reply runSale(Sale sale) {        boolean finished = false;        try {            Reply reply = sale.byCard() ? runCardSale(sale) : runCashSale(sale);            finished = true;            return reply;        } finally {            if (!finished) {                abandon(sale);            }        }    }

abandon checks that this sale is still the active one. Then it blocks the slot if vend had started the spiral, puts a card key into pendingVoids, and returns to HasMoney if cash is in escrow, or to Ready. The exception then goes on to the caller.

The operator

The operator presses the service button, and the controller releases the door lock only when openDoor returns a session:

machine/VendingMachine.javalines 121–130 of 434
    /** The service button. The controller unlocks the door only if this returns a session. */    public Optional<ServiceSession> openDoor() {        synchronized (lock) {            if (!state.openDoor(this)) {                return Optional.empty();            }            session = new ServiceSession(this);            return Optional.of(session);        }    }

Only Ready gives a session (line 124). HasMoney refuses, because a customer's cash is in escrow. If the customer walked away and left it, the operator presses cancel, which drops that cash into the tray, and tries again. Vending refuses, because a product is on its way. Otherwise the machine creates a ServiceSession (line 127), and Maintenance turns customers away.

machine/ServiceSession.javalines 21–46 of 111
    /** An empty slot takes any product. A slot with items left takes more of the same product. */    public void load(String code, String product, long priceCents, int count) {        Objects.requireNonNull(code, "code");        Objects.requireNonNull(product, "product");        if (count <= 0) {            throw new IllegalArgumentException("Load at least one item, not " + count);        }        synchronized (machine.lock()) {            machine.requireOpen(this);            if (!machine.isSlotCode(code)) {                throw new IllegalArgumentException("There is no slot " + code);            }            Slot current = machine.slotAt(code);            Slot loaded;            if (current != null && current.jammed()) {                throw new IllegalArgumentException("Clear the jam in " + code + " first");            } else if (current == null || current.count() == 0) {                loaded = new Slot(code, product, priceCents, count, machine.slotCapacity(), false);            } else if (current.product().equals(product)) {                loaded = current.withPrice(priceCents).withMore(count);            } else {                throw new IllegalArgumentException(code + " still holds " + current.count() + " " + current.product());            }            machine.putSlot(loaded);        }    }

Every method takes the machine's lock and checks that this session is still the open one (lines 28 and 29). A slot that holds items takes only more of the same product. An empty slot takes any product, and a jammed one takes nothing until clearJam has recorded what is left (lines 35 to 43).

machine/ServiceSession.javalines 89–102 of 111
    /** Empties the cash box and returns what was in it, for the operator's bag. */    public CashCount collectCashBox() {        synchronized (machine.lock()) {            machine.requireOpen(this);            return machine.takeCashBox();        }    }     /** Ends maintenance. A second close does nothing. */    public void close() {        synchronized (machine.lock()) {            machine.endService(this);        }    }

collectCashBox hands the notes and coins in the cash box to the operator and empties it, under the same lock (line 93). close ends maintenance (line 100), and a second close does nothing, so a double press on the panel is harmless.

Decision

How do operator actions stay out of customers' reach?

Operator methods on VendingMachine, each checking for Maintenance

There is one class to call. But every new operator action needs the same check, and a forgotten one lets the panel's code restock a machine with a customer at it.

openDoor returns a ServiceSession, and only it can change slots, prices and coinsOur pick

Code without a session cannot reach the operator's methods, and a closed session refuses everything. The state classes stay at five actions, and adding an operator action touches no state. The cost is one more class, and a check in each method that the session is still open.

A price changes the same way, through setPrice on the session. Since the door opens only in Ready, no customer has money in while a price changes. A sale also copies the price into its Sale record when it starts, so it keeps that price after the lock is let go.

Decision

When does a new price apply?

At once, from anywhere, read when the product drops

The office can change prices remotely. But a customer could insert $1.25 for pretzels and find them $1.40 when the product drops. The machine would then have sold for less than the price, or refused a sale it had already started.

Only through an open ServiceSession, and a sale keeps the price it started withOur pick

The label, the screen and the charge always agree. The cost is that a price changes only on a visit. Prices sent from the office are a follow-up below.

Many callers, one machine

The keypad, the coin slot, the card reader, the door switch and the retry timer each call the machine from their own thread. Every field that changes is guarded by one private lock. It is held for checks and field changes only. The card network, the dispenser and the coin tray are never called while it is held. VendingState guards the slow part instead.

Two presses on one payment
$1.25 is in escrow and two presses of A1 arrive together. On the left there is no lock. Both read HasMoney with $1.25 in. The first drop keeps the $1.25, and the second finds the escrow empty and keeps nothing, so two pretzels go out for one payment. On the right, select runs the state under the lock. Press A checks the money and moves to Vending before letting go. Press B waits, finds Vending and gets WAIT, so one pretzel drops.$1.25 is in escrow and two presses of A1 arrive together. On the left there is no lock. Both read HasMoney with $1.25 in. The first drop keeps the $1.25, and the second finds the escrow empty and keeps nothing, so two pretzels go out for one payment. On the right, select runs the state under the lock. Press A checks the money and moves to Vending before letting go. Press B waits, finds Vending and gets WAIT, so one pretzel drops.
Without the lock, both presses can see the money. $1.25 is in escrow and two presses of A1 arrive together. On the left there is no lock. Both read HasMoney with $1.25 in. The first drop keeps the $1.25, and the second finds the escrow empty and keeps nothing, so two pretzels go out for one payment. On the right, select runs the state under the lock. Press A checks the money and moves to Vending before letting go. Press B waits, finds Vending and gets WAIT, so one pretzel drops.

The project includes demo/RaceCheck.java. It puts $1.25 into the machine, releases two presses of A1 at the same moment, and repeats this 2,000 times:

$ java demo.RaceCheck
2000 rounds of two presses on A1 at $1.25
products dropped: 2000
money taken: $2500.00
rounds that dropped two: 0

Every round sold exactly one product, and the money matches. We also ran it in a scratch copy with the lock taken off select. That copy also caught the crashes and cleared the jams they left, so a run could finish. In those runs, about one round in ten dropped two pretzels for one $1.25, and a few rounds crashed when a slot's count would have gone below zero. The exact numbers change from run to run and from machine to machine.

The final design

VendingMachine is the core. It owns the slots, the escrow, the tubes, the cash box, the open ServiceSession and the payments still to settle, all under one lock. It hands every customer action to a MachineState, and reaches the card network, the motors and the coin tray only through PaymentProcessor, Dispenser and CoinReturn. The lock is held only while state changes. A sale that is waiting on the network or the motor is guarded by its state instead, and no money is kept until the sensor sees a product.

The design we built
The classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. VendingMachine carries 4 and 5, MachineState carries 2, ChangePlanner carries 3, and ServiceSession carries 7. Among the records, CashCount carries 1, Slot carries 6 and Sale carries 8. A purple tag marks MachineState as the State pattern.The classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. VendingMachine carries 4 and 5, MachineState carries 2, ChangePlanner carries 3, and ServiceSession carries 7. Among the records, CashCount carries 1, Slot carries 6 and Sale carries 8. A purple tag marks MachineState as the State pattern.
Each decision lands on one class. One interface carries a pattern. The classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. VendingMachine carries 4 and 5, MachineState carries 2, ChangePlanner carries 3, and ServiceSession carries 7. Among the records, CashCount carries 1, Slot carries 6 and Sale carries 8. A purple tag marks MachineState as the State pattern.
S.No.The questionWhat we choseWhy
1Keep a balance, or keep the coins?The coins themselves, in an escrow CashCountCancel returns the same coins, and they can pay change
2Is a sale in progress a state of its own?Yes: VendingState, and the lock is held only to change stateSlow calls run unlocked while a second press gets WAIT
3When does the machine decide it can give change?Before the spiral turns, from the tubes and the customer's coinsA refusal costs nothing
4Charge the card and refund a jam, or hold, then capture?Hold before the spiral turns, capture after the drop, void after a jamMoney moves only after the sensor sees the product
5The card gets no answer. Ask again, or give up the sale?Give up the sale and void the keyOne timeout, and no hold survives
6Nothing dropped. Who keeps the money?The customer pays nothing, the slot is blocked, and a silent motor counts as a jamNobody pays for a product nobody saw
7How do operator actions stay out of customers' reach?openDoor returns a ServiceSession, and only it can change slots, prices and coinsCode without a session cannot reach them
8When does a new price apply?Only through an open ServiceSession, and a sale keeps the price it started withThe label, the screen and the charge agree

Here is Farah's card purchase from the demo, end to end:

  1. The reader calls tapCard("A2", token), which takes the lock. ReadyState.tapCard checks cannotSell, creates a Sale with a random key, and startSale sets VendingState. The lock is released.
  2. runCardSale calls PaymentProcessor.authorize for $1.50 with no lock held. This is the outside call, and it answers APPROVED.
  3. vend calls Dispenser.vend("A2"), still with no lock held, and the sensor answers DROPPED.
  4. runCardSale takes the lock again. withOneLess makes the new Slot, the key goes into pendingCaptures, and endSale sets ReadyState.
  5. sendCapture calls capture with no lock held, and removes the key once the processor takes it. If the capture had got no answer, the key would wait for the timer.

A cash sale follows the same steps without the network. HasMoneyState.select makes the change plan in step 1, under the lock, and completeCashSale moves the coins in step 4, after the drop. A jam would have ended at step 3 instead: the slot is blocked, and the hold is voided or the cash stays in escrow.

The complete code

Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.

machineVendingMachine.java
package machine; import java.util.ArrayList;import java.util.Collections;import java.util.LinkedHashSet;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.Set;import java.util.TreeMap;import java.util.TreeSet; import hardware.CoinReturn;import hardware.Dispenser;import hardware.VendResult;import money.Cash;import money.CashCount;import money.Dollars;import payment.AuthResult;import payment.PaymentProcessor;import slot.Slot; /** * The machine: its slots, the cash it holds and the sale in progress. Every * field that changes is guarded by lock. The card processor, the dispenser * and the coin tray are never called while it is held. */public class VendingMachine {    public static final long MAX_ESCROW_CENTS = 2_000;    public static final int TUBE_CAPACITY = 60;    public static final int MAX_SLOT_CAPACITY = 20;     private final Object lock = new Object();    private final Set<String> slotCodes;    private final int slotCapacity;    private final Dispenser dispenser;    private final CoinReturn coinReturn;    private final PaymentProcessor payments;     private final Map<String, Slot> slots = new TreeMap<>();    private final Set<String> pendingCaptures = new LinkedHashSet<>();    private final Set<String> pendingVoids = new LinkedHashSet<>();    private MachineState state = new ReadyState();    private CashCount escrow = CashCount.NONE;    private CashCount tubes = CashCount.NONE;    private CashCount cashBox = CashCount.NONE;    private Sale activeSale;    private boolean spiralTurned;    private ServiceSession session;     public VendingMachine(List<String> slotCodes, int slotCapacity, Dispenser dispenser, CoinReturn coinReturn,            PaymentProcessor payments) {        Objects.requireNonNull(slotCodes, "slotCodes");        Set<String> codes = new TreeSet<>();        for (String code : slotCodes) {            Objects.requireNonNull(code, "slot code");            if (!Slot.CODE.matcher(code).matches()) {                throw new IllegalArgumentException("A slot code is a letter A to F and a digit 1 to 9, not " + code);            }            if (!codes.add(code)) {                throw new IllegalArgumentException("Slot " + code + " is listed twice");            }        }        if (codes.isEmpty()) {            throw new IllegalArgumentException("A machine needs at least one slot");        }        if (slotCapacity <= 0 || slotCapacity > MAX_SLOT_CAPACITY) {            throw new IllegalArgumentException("A spiral holds 1 to " + MAX_SLOT_CAPACITY + " items, not " + slotCapacity);        }        this.slotCodes = Collections.unmodifiableSet(codes);        this.slotCapacity = slotCapacity;        this.dispenser = Objects.requireNonNull(dispenser, "dispenser");        this.coinReturn = Objects.requireNonNull(coinReturn, "coinReturn");        this.payments = Objects.requireNonNull(payments, "payments");    }     // ------------------------------------------------------------ customer actions     public Reply insert(Cash cash) {        Objects.requireNonNull(cash, "cash");        Reply reply;        synchronized (lock) {            reply = state.insert(this, cash);        }        return handBack(reply);    }     public Reply select(String code) {        Objects.requireNonNull(code, "code");        Step step;        synchronized (lock) {            step = state.select(this, code);        }        return step.sale() == null ? handBack(step.reply()) : runSale(step.sale());    }     public Reply tapCard(String code, String cardToken) {        Objects.requireNonNull(code, "code");        Objects.requireNonNull(cardToken, "cardToken");        if (cardToken.isBlank()) {            throw new IllegalArgumentException("The card reader sent an empty token");        }        Step step;        synchronized (lock) {            step = state.tapCard(this, code, cardToken);        }        return step.sale() == null ? handBack(step.reply()) : runSale(step.sale());    }     public Reply cancel() {        Reply reply;        synchronized (lock) {            reply = state.cancel(this);        }        return handBack(reply);    }     // ------------------------------------------------------------ operator and timer     /** The service button. The controller unlocks the door only if this returns a session. */    public Optional<ServiceSession> openDoor() {        synchronized (lock) {            if (!state.openDoor(this)) {                return Optional.empty();            }            session = new ServiceSession(this);            return Optional.of(session);        }    }     /** A timer calls this. Sends every capture and void that got no answer again; returns how many went through. */    public int retryPayments() {        List<String> captures;        List<String> voids;        synchronized (lock) {            captures = new ArrayList<>(pendingCaptures);            voids = new ArrayList<>(pendingVoids);        }        int settled = 0;        for (String key : captures) {            if (sendCapture(key)) {                settled++;            }        }        for (String key : voids) {            if (sendVoid(key)) {                settled++;            }        }        return settled;    }     // ------------------------------------------------------------ a sale, run without the lock     private Reply runSale(Sale sale) {        boolean finished = false;        try {            Reply reply = sale.byCard() ? runCardSale(sale) : runCashSale(sale);            finished = true;            return reply;        } finally {            if (!finished) {                abandon(sale);            }        }    }     private Reply runCashSale(Sale sale) {        VendResult result = vend(sale);        Reply reply;        synchronized (lock) {            reply = result == VendResult.DROPPED ? completeCashSale(sale) : jamCashSale(sale);        }        return handBack(reply);    }     /** Lock held. The product dropped, so the escrow is kept and the change planned at the start goes out. */    private Reply completeCashSale(Sale sale) {        CashCount pool = tubes.plus(escrow.tubeCoins()).minus(sale.change());        CashCount newTubes = pool.atMost(TUBE_CAPACITY);        CashCount notes = escrow.minus(escrow.tubeCoins());        CashCount newCashBox = cashBox.plus(notes).plus(pool.minus(newTubes));        Slot sold = slots.get(sale.slotCode()).withOneLess();        // Everything that can throw has run. Only now does the state change.        slots.put(sale.slotCode(), sold);        tubes = newTubes;        cashBox = newCashBox;        escrow = CashCount.NONE;        endSale(new ReadyState());        return new Reply(Outcome.VENDED, "Enjoy your " + sale.product(), sale.change());    }     /** Lock held. Nothing dropped: the slot is blocked and the cash stays in escrow. */    private Reply jamCashSale(Sale sale) {        slots.put(sale.slotCode(), slots.get(sale.slotCode()).jam());        endSale(new HasMoneyState());        return Reply.of(Outcome.JAMMED, sale.slotCode() + " is out of order. Your "                + Dollars.format(escrow.totalCents()) + " is still in. Pick another or press cancel");    }     private Reply runCardSale(Sale sale) {        String key = sale.paymentKey();        AuthResult answer;        try {            answer = Objects.requireNonNull(payments.authorize(key, sale.cardToken(), sale.priceCents()), "answer");        } catch (RuntimeException noAnswer) {            // A hold may exist, or may still arrive. Voiding the key covers both.            synchronized (lock) {                pendingVoids.add(key);                endSale(new ReadyState());            }            sendVoid(key);            return Reply.of(Outcome.NO_ANSWER, "No answer from the card network. Nothing was charged");        }        if (answer == AuthResult.DECLINED) {            synchronized (lock) {                endSale(new ReadyState());            }            return Reply.of(Outcome.DECLINED, "Card declined");        }        VendResult result = vend(sale);        if (result == VendResult.DROPPED) {            synchronized (lock) {                Slot sold = slots.get(sale.slotCode()).withOneLess();                slots.put(sale.slotCode(), sold);                pendingCaptures.add(key);                endSale(new ReadyState());            }            sendCapture(key);            return Reply.of(Outcome.VENDED, "Enjoy your " + sale.product());        }        synchronized (lock) {            slots.put(sale.slotCode(), slots.get(sale.slotCode()).jam());            pendingVoids.add(key);            endSale(new ReadyState());        }        sendVoid(key);        return Reply.of(Outcome.JAMMED, sale.slotCode() + " is out of order. Your card was not charged");    }     private VendResult vend(Sale sale) {        synchronized (lock) {            spiralTurned = true;        }        try {            VendResult result = dispenser.vend(sale.slotCode());            return result == null ? VendResult.JAMMED : result;        } catch (RuntimeException motorFault) {            // Nobody saw a product drop, so the customer does not pay for one.            return VendResult.JAMMED;        }    }     /** Something escaped mid-sale. Block the slot if it turned, keep any cash in escrow, and leave a hold to be voided. */    private void abandon(Sale sale) {        synchronized (lock) {            if (activeSale != sale) {                return;            }            if (spiralTurned) {                slots.computeIfPresent(sale.slotCode(), (code, slot) -> slot.jam());            }            if (sale.byCard()) {                pendingVoids.add(sale.paymentKey());            }            endSale(escrow.isEmpty() ? new ReadyState() : new HasMoneyState());        }    }     private boolean sendCapture(String key) {        try {            payments.capture(key);        } catch (RuntimeException noAnswer) {            return false;        }        synchronized (lock) {            pendingCaptures.remove(key);        }        return true;    }     private boolean sendVoid(String key) {        try {            payments.voidHold(key);        } catch (RuntimeException noAnswer) {            return false;        }        synchronized (lock) {            pendingVoids.remove(key);        }        return true;    }     /** No lock held: the tray is hardware. */    private Reply handBack(Reply reply) {        if (!reply.returned().isEmpty()) {            coinReturn.pay(reply.returned());        }        return reply;    }     // ------------------------------------------------------------ reads     public Optional<Slot> slot(String code) {        synchronized (lock) {            return Optional.ofNullable(slots.get(code));        }    }     public CashCount escrow() {        synchronized (lock) {            return escrow;        }    }     public CashCount tubes() {        synchronized (lock) {            return tubes;        }    }     public CashCount cashBox() {        synchronized (lock) {            return cashBox;        }    }     public Set<String> pendingCaptures() {        synchronized (lock) {            return Set.copyOf(pendingCaptures);        }    }     public Set<String> pendingVoids() {        synchronized (lock) {            return Set.copyOf(pendingVoids);        }    }     public String stateName() {        synchronized (lock) {            return state.getClass().getSimpleName();        }    }     // ------------------------------------------------------------ for the states and the service session     // Package-private, and called with the lock held.    void changeState(MachineState next) {        state = next;    }     void startSale(Sale sale) {        activeSale = sale;        spiralTurned = false;        state = new VendingState();    }     private void endSale(MachineState next) {        activeSale = null;        state = next;    }     /** False if this would take the escrow over the limit. */    boolean addToEscrow(Cash cash) {        long total = Math.addExact(escrow.totalCents(), cash.cents());        if (total > MAX_ESCROW_CENTS) {            return false;        }        escrow = escrow.plus(CashCount.of(cash, 1));        return true;    }     CashCount takeEscrow() {        CashCount all = escrow;        escrow = CashCount.NONE;        return all;    }     Optional<Reply> cannotSell(String code) {        if (!slotCodes.contains(code)) {            return Optional.of(Reply.of(Outcome.UNAVAILABLE, "There is no slot " + code));        }        Slot slot = slots.get(code);        if (slot == null) {            return Optional.of(Reply.of(Outcome.UNAVAILABLE, code + " is empty"));        }        return slot.whyNotForSale().map(why -> Reply.of(Outcome.UNAVAILABLE, why));    }     Slot slotAt(String code) {        return slots.get(code);    }     Object lock() {        return lock;    }     boolean isSlotCode(String code) {        return slotCodes.contains(code);    }     int slotCapacity() {        return slotCapacity;    }     void putSlot(Slot slot) {        slots.put(slot.code(), slot);    }     void setTubes(CashCount newTubes) {        tubes = newTubes;    }     CashCount takeCashBox() {        CashCount all = cashBox;        cashBox = CashCount.NONE;        return all;    }     void requireOpen(ServiceSession caller) {        if (session != caller) {            throw new IllegalStateException("This service session is closed");        }    }     void endService(ServiceSession caller) {        if (session == caller) {            session = null;            state = new ReadyState();        }    }}
Click a class name in the code to open its fileJava · 434 lines · 1445 in the project

demo/Main.java runs a morning at one machine. The operator loads four slots and leaves only a dime and a nickel for change. Meera, Asha and Ravi pay cash. Dev, Esha and Farah tap cards, a spiral jams, and the network loses a reply. Then the operator clears the jam, raises a price and collects the cash box:

$ java demo.Main
-- 7:00 the operator fills the machine, with little change
tubes: $0.15 (1 x NICKEL, 1 x DIME)
-- 8:10 Meera pays $1.75 in a note and three quarters for a $1.50 bar
Meera, select A2: VENDED. Enjoy your Granola bar  [tray: $0.25 (1 x QUARTER)]
tubes: $0.65 (1 x NICKEL, 1 x DIME, 2 x QUARTER)
-- 8:25 Asha buys pretzels
Asha, select A1: NOT_ENOUGH_MONEY. Pretzels is $1.25. Insert $0.25 more
Asha, insert QUARTER: ACCEPTED. Inserted $1.25
Asha, select A1: VENDED. Enjoy your Pretzels
-- 8:40 Ravi wants gum and has a $5 note
Ravi, select B2: NO_CHANGE. Exact change only: no coins for $4.15 change. Pick another or press cancel
Ravi, cancel: CANCELLED. Returned $5.00  [tray: $5.00 (1 x FIVE_DOLLAR_NOTE)]
Ravi, select B2: VENDED. Enjoy your Gum  [tray: $0.15 (1 x NICKEL, 1 x DIME)]
tubes: $0.75 (3 x QUARTER)
-- 9:05 cards
Dev, card, B1: JAMMED. B1 is out of order. Your card was not charged
Esha, card, A1: DECLINED. Card declined
Esha, card, A1: NO_ANSWER. No answer from the card network. Nothing was charged
voids waiting: 1
Farah, card, A2: VENDED. Enjoy your Granola bar
timer: 1 sent, voids waiting: 0
-- 10:00 the operator clears B1 and raises the pretzels
Gita, insert QUARTER: OUT_OF_SERVICE. Out of service for a few minutes  [tray: $0.25 (1 x QUARTER)]
collected: $3.00 (1 x DOLLAR_COIN, 2 x ONE_DOLLAR_NOTE)
Gita, select A1: PRICE_SHOWN. Pretzels $1.40. Insert cash or tap a card
-- 10:05 the machine
A1 Pretzels $1.40, 4 left
A2 Granola bar $1.50, 2 left
B1 Iced tea $2.35, 2 left
B2 Gum $0.85, 5 left
tubes: $0.75 (3 x QUARTER)
cash box: nothing
cards: 1 captured ($1.50), 2 voided, 0 still held

Notice three things in the output. Meera's change is one of her own quarters, because the tubes alone held only 15 cents. Ravi's $5 note is refused before anything moves, and cancel returns the same note. And the cards line shows one capture of $1.50 and two voids: Dev's jam, and Esha's lost reply, whose void went through on the timer's first run.

Follow-up questions

After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Change prices from the office."The machine keeps a list of new prices and applies it the next time it is Ready.Sale still keeps its own price, and the states stay the same.
"Give change in dollar coins too."Cash.DOLLAR_COIN becomes a tube coin, and ChangePlanner tries one more coin size.VendingMachine and the states.
"Tell the operator when a slot runs low."A listener interface, called after a sale with no lock held. A listener that throws must not undo the sale.The sale flow and the lock.
"The coin tray can jam."Today the escrow or the change is cleared before the tray pays, so a tray that throws loses track of those coins. CoinReturn.pay would report what it paid, and the machine would record the shortfall and block cash sales until an operator looks.Card sales and the change plan.
"Pay part in cash and the rest by card."HasMoneyState.tapCard stops refusing, and a Sale holds both the escrow and a hold for the rest. This changes Sale and two states.The hold, capture and void order.
"Some products need an age check."Slot gains a flag. A cash sale of such a product is refused, and a card sale asks the network to confirm the age.The other slots and the change rule.
"Try the spiral again before calling it a jam."Inside Dispenser, which can watch the motor.VendingMachine, which still sees one answer.
"Survive a power cut."The escrow, pendingCaptures and pendingVoids move to storage on the controller. The keys are UUIDs already, so none repeats after a restart.The order of hold, drop and capture.
"Run a fleet of 500 machines."Each machine stays its own object. A back office collects sales and sends prices.Everything inside one machine.

In most rows the change lands in one class or one interface. Two rows are bigger: mixed payment touches Sale and two states, and a jammed tray adds a new failure the money path must record.

What the interviewer looks for

Mid-level

A mid-level candidate shows the states, keeps money in integer cents, and refuses a sale when the money is short. They hand back the money on cancel and make the second press of a button harmless, even if the lock covers more than it needs to.

Senior

A senior candidate shows everything above and gives the order of the steps. They plan the change before the spiral turns, using the customer's own coins. They hold the card before the drop and capture after it. They block a jammed slot and charge nothing for it, and they keep the network and the motor outside the lock.

Staff+

A staff candidate leads with the failure cases. They point out that a card call has three outcomes and void a key that got no answer. They keep failed captures and voids for retry, and they use keys that never repeat across restarts. They say what must be stored to survive a power cut, and which failures still need a person.

Common mistakes

  • A balance instead of the coins. Cancel then has to pay back from the tubes, which may not hold the right coins.
  • Assuming there is always change. The customer is short-changed, or the product is gone before the machine finds out it cannot pay.
  • Charging the card before the drop. A jam turns into a charge and a refund.
  • Treating no answer as a decline. A hold placed by the lost call can stay on the card.
  • A new key for every retry. The network sees two payments where there was one.
  • Holding the lock while the motor turns. The door, the reads and every other button wait for seconds.

Summary

  • Keep the customer's coins in escrow, not a balance. Cancel returns them, and they can pay change.
  • Plan the change before the spiral turns, so a refusal costs nothing.
  • Hold the card before the drop, capture after it, and void after a jam or a lost reply.
  • Keep failed captures and voids, and send them again with the same UUID key.
  • A jam, or a motor that cannot say what happened, costs the customer nothing and blocks the slot.
  • The State pattern gives each situation its own class, and VendingState guards the slow calls while the lock is free.
  • Only a ServiceSession from an open door can restock, change prices, clear a jam or collect the cash.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.