AlgoViz

Design an inventory management system

medium 80 min

Count goods in several places, promise them to orders without ever promising too much, ship or let go, and explain every count.

Watch lesson4:28

Verify

Trace it before you say done

The point: run the code by hand on one good day and on every bad one, and write the two counts after each call.

Trace

The program from the code tab

Callcellar plumshed plumcellar figAnswer
deliveries6 / 03 / 04 / 0
reserve a: plum 2, fig 16 / 03 / 24 / 1Picks from shed and cellar; alert for the shed
reserve b: fig 1, plum 96 / 03 / 24 / 1OutOfStock, nothing changed
ship a6 / 01 / 03 / 0Two movements
reserve c: plum 56 / 51 / 03 / 0Cellar only; alert for the cellar (1 left)
expire at 10006 / 01 / 03 / 01 promise closed
ship c6 / 01 / 03 / 0NotHeld
Each cell is on hand / held. Order c could have used the shed too, but the cellar alone is enough: one parcel.

Edges

Small inputs that break large designs

InputExpectedWhich line does it
Want exactly what is availableHeld, available 0qty <= self.available
Want 0 or -1ValueErrorFirst lines of reserve
Want nothing at allValueErrornot wanted
Unknown productOutOfStockThe policy sees no lines and answers None
Unknown place in receiveKeyErrorGoods are never invented for a place
Ship twiceNotHeldStatus is SHIPPED
Release after shipNotHeldSame check
Ship in the second of the endNotHeldexpires_at <= now
Listener raises an exceptionThe promise standsIt is told after the block

Invariants

Four sentences, checked by a program

Python
def check(shop):    for (sku, place), line in shop._lines.items():        assert 0 <= line.held <= line.on_hand        moved = sum(m.change for m in shop._movements if (m.sku, m.place) == (sku, place))        assert moved == line.on_hand        promised = sum(p.qty for r in shop._reservations.values() if r.status is Status.HELD                       for p in r.picks if (p.sku, p.place) == (sku, place))        assert promised == line.held
Call it after each step of a test. A test may look inside; a caller may not.

Which rule broke tells you where to look

Good invariants are also a map of the bugs.