Design an online shop
hard 90 minModel a catalog, a cart, stock and orders as objects, and write a checkout that holds the goods, gets the money and sells, with a way back from every step.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Calls travel between objects, stock and money move one after the other, and the matching lines light up.
Operations
A wish in the cart
Ids and numbers. No price, no stock.
Step 1 of 6
Empty
The page knows the cart. The catalog knows prices. They do not know each other.
Step 1: Empty
def set(self, product_id, quantity): if not 0 <= quantity <= 99: raise ShopError("quantity must be 0 to 99") if quantity == 0: self._quantities.pop(product_id, None) else: self._quantities[product_id] = quantity self.version += 1def add(self, product_id, quantity=1): if quantity < 1: raise ShopError("add at least one") self.set(product_id, self._quantities.get(product_id, 0) + quantity)- Cost
- O(1)
- Guarantee
- One row for a product
- As a list
- O(n), duplicates
Nothing in a cart can be out of date.
In the real world
The same online shop doing real jobs. Pick one and step through it.
The same key twice, the first still running.
Step 1 of 4
First click
The order is stored and the bank is asked.
Step 1: First click
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Money before stock
criticalPeople pay for goods that are gone.
Wrongpayment.charge(total)inventory.reserve(lines)Rightif inventory.reserve(key, lines): payment.authorize(key, total)Ignoring the answer
criticalreserve and sell can say no. The order is confirmed anyway.
Wronginventory.reserve(p, n)order.status = "PROCESSING"Rightif not inventory.sell(key): payments.void(key) order.move(CANCELLED)Timeout means no
criticalThe bank may hold the money of a cancelled order.
Wrongexcept Exception: order.cancel()Rightexcept Declined: undo()except Timeout: pass # PENDING, ask again with the same keyRelease by number
majorTwice, or for something that was never held: goods from nothing.
Wrongreserved[p] -= nRightholds.pop(order_key, None)A live price in the order
majorReceipts change when a tag changes.
Wrongtotal = sum(i.product.price * i.n for i in order.items)RightLine(p.id, p.name, p.cents, n) # copied onceTrusting the total
majorA hand-made request pays one cent.
Wrongcharge(request.total)Rightif bill.total != request.seen_total: ask_again(bill.total)
Interview tips
Open with
- Four speeds, four objects.
- Hold, money, sale.
- One key for each order.
Reject aloud
- Customer is an id.
- A variant is a product.
- No stock in Product.
Prove it
- The last piece.
- A double click.
- Stop after authorise.
Never
- A float for money.
- Two counters for one truth.
- Undo a sale for a mail.