Discover the Rules
What must always remain true? quantity > 0, one entry per product, a total that is never negative. Rules determine implementation: rule → validation → `if quantity <= 0: reject`. Then inject a new constraint and follow it through.
For each operation, ask what must always remain true afterwards. The cart's answers — quantity > 0, one entry per product, a total that is never negative, no unknown product, quantity within stock if inventory is enforced here — are not comments on the code; they are the reason the code has the lines it has.
Rule → validation → code, for every cart rule. "Every quantity is greater than zero" becomes "reject a quantity ≤ 0" becomes `if quantity <= 0: reject`. Code is a precise encoding of a previously identified rule — which is why an `if` you cannot name the rule for is suspicious.
The example "[Laptop × 1], add Laptop → [Laptop × 2]" is where the rule "one entry per product" was discovered. Rules you write down in the abstract are the obvious ones; the ones that shape the code arrive when you write what should happen and notice you had to decide.
The cart works. Now: "quantity may not exceed 10". Follow the new requirement through the same path the original rules took — invariant → example → implementation → test — and notice that it touches exactly one rule, two examples, two functions and one test, which is how you know the earlier work was right.
Not every cart rule is the cart's to enforce. Stock belongs to inventory, price to the catalog, and uniqueness — once there are rows — also to a database constraint. Ask who is authoritative for each rule; a cart that enforces stock alone is a race the inventory service has to resolve at checkout anyway.