Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Draw the order states (20 minutes)
Draw all order states and allowed arrows. Mark which ones allow cancelling.
Done when: the drawing has seven states, and cancel arrows leave only placed and accepted.
Hint
Cancel is only allowed before the kitchen starts.
Easy 2: Run the app (20 minutes)
Type the code and reproduce the first four rows of the run table.
Done when: you print 100000, 10000, 4000, 94000, then "out of stock" with cola stock 8.
Hint
The listener can add strings to a list.
Easy 3: Price by hand (20 minutes)
A cart has 3 items at 20000 and 1 item at 15000. The discount is 10 per cent over 50000, and the fee is 3000. Work out the total.
Done when: you write subtotal 75000, discount 7500, and total 70500.
Hint
3 x 20000 + 15000 = 75000, and 10 per cent of 75000 is 7500.
Medium
Medium 1: Delivery fee strategy (45 minutes)
Add a DeliveryFee interface with a flat fee and a fee by distance, and use it in place.
Done when: two tests show the two fees, and place has no if on fee type.
Hint
The fee depends on the order and the address, so pass both in.
Medium 2: Atomic order ids (45 minutes)
Fix the id counter with AtomicInteger. Place 1,000 orders from 8 threads.
Done when: a check shows 1,000 distinct ids, and the old version fails the same test at least once.
Hint
incrementAndGet returns the new value.
Medium 3: Item options (45 minutes)
Let a line carry options with extra prices, such as a large size for 20.00 more. Include them in totals and keep them in the snapshot.
Done when: a test shows the total with options, and a later change to an option price leaves the old order unchanged.
Hint
A line total is quantity times the price plus its options.
Hard
Hard 1: Race for the last item (90 minutes)
Run 100 threads each trying to order the last item, and prove exactly one succeeds and the stock never goes negative.
Done when: a check prints one winner and stock zero, and a version with item-by-item taking fails the check.
Hint
Use a start latch so all threads begin at once.
Hard 2: Payment step (90 minutes)
Add a payment interface. Place the order, call payment, and on failure cancel and return the stock. Test a gateway that fails every second call.
Done when: stock plus ordered units always equals the starting stock, and failed payments leave cancelled orders.
Hint
Place first, pay second, cancel on failure.
Hard 3: Delivery partner matching (90 minutes)
Add an assigned state and a partner matcher like module 7's driver matcher. Reuse its atomic reserve idea.
Done when: a test with 3 partners and 10 ready orders never gives a partner two orders at once.
Hint
Compare with the tryReserve method of the driver.