CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 4 of 6 · 4 min read

The code

Cart checks, stock and the state table.

The cart refuses bad input at the door (Level 5, module 1):

class Cart {
    final Restaurant r; final Map<String, Integer> qty = new LinkedHashMap<>();
    void add(String itemId, int n) {
        if (n < 1) throw new IllegalArgumentException("quantity must be at least 1");
        if (!r.menu.containsKey(itemId)) throw new IllegalArgumentException("not on this menu: " + itemId);
        qty.merge(itemId, n, Integer::sum);
    }
}

The restaurant takes stock for the whole cart in one synchronized step. The first loop only checks. The second loop only writes. This is the same two-loop shape as the seat hold in module 5.

synchronized boolean tryTake(Map<String, Integer> want) {
    for (var e : want.entrySet())
        if (stock.getOrDefault(e.getKey(), 0) < e.getValue()) return false;
    for (var e : want.entrySet()) stock.merge(e.getKey(), -e.getValue(), Integer::sum);
    return true;
}
synchronized void putBack(Map<String, Integer> back) {
    for (var e : back.entrySet()) stock.merge(e.getKey(), e.getValue(), Integer::sum);
}

The order has a table of legal moves, and tells its listeners after each one. The lock covers only the check and the change of state. Listeners are called outside the lock, so a slow listener cannot block other threads (Level 4, module 2).

private static final Map<OrderState, Set<OrderState>> NEXT = Map.of(
    PLACED,    Set.of(ACCEPTED, CANCELLED),
    ACCEPTED,  Set.of(PREPARING, CANCELLED),
    PREPARING, Set.of(READY),
    READY,     Set.of(PICKED_UP),
    PICKED_UP, Set.of(DELIVERED),
    DELIVERED, Set.of(),
    CANCELLED, Set.of());

void move(OrderState next) {
    OrderState from;
    synchronized (this) {
        if (!NEXT.get(state).contains(next)) throw new IllegalStateException(state + " -> " + next);
        from = state; state = next;
    }
    if (next == OrderState.CANCELLED) {          // give the stock back
        Map<String, Integer> back = new HashMap<>();
        for (Line l : lines) back.put(l.item().id(), l.qty());
        r.putBack(back);
    }
    for (Listener l : ls) l.onChange(this, from, next);
}

Only the states placed and accepted allow cancelling, so food that is already cooking cannot be cancelled and the stock never comes back for it.

The app places the order. It checks that the cart is not empty, takes stock, works out the money in cents, and announces the new order:

Order place(Cart c) {
    List<Line> lines = c.lines();
    if (lines.isEmpty()) throw new IllegalStateException("cart is empty");
    if (!c.r.tryTake(c.qty)) throw new IllegalStateException("out of stock");
    long sub = 0; for (Line l : lines) sub += l.total();
    Order o = new Order("O" + (++seq), c.r, lines, discount.off(sub), deliveryFee, listeners);
    for (Listener l : listeners) l.onChange(o, null, OrderState.PLACED);
    return o;
}

The discount is a strategy. PercentOff(10, 50000) gives 10 per cent off when the subtotal is at least 500.00.

A run. The restaurant has 3 pizzas at 300.00 and 10 colas at 50.00. The discount is 10 per cent over 500.00, and the delivery fee is 40.00. All amounts are cents, and the amounts are made up to show the idea.

Step Result
Cart: 2 pizzas, 2 colas, then 1 more pizza. Place it Subtotal 100000, discount 10000, delivery 4000, total 94000. Pizza stock is 0
A second cart asks for 1 pizza Refused: "out of stock". Cola stock is still 8, so nothing was taken
Move the order through accepted, preparing, ready, picked up, delivered Each move allowed
Try to cancel the delivered order Refused: "DELIVERED -> CANCELLED"
A new order of 4 colas Subtotal 20000, no discount (under the minimum), total 24000. Cola stock is 4
Accept it, then cancel it Cola stock is back to 8
Listener log O1 placed, accepted, preparing, ready, picked up, delivered, then O2 placed, accepted, cancelled
Item not on the menu, quantity 0, empty cart Refused with clear messages

Check yourself: 1. Why are listeners called outside the lock? 2. Why can an order not be cancelled once it is preparing? 3. What is the total for 20000 of items with no discount and a 4000 fee?