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.

Rules Determine Implementation

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.

Q · You know the cart's operations. Before writing any of them, what must always remain true — and how does each answer turn into a line of code?
From Invariant to Validation
▶ lab

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.

Q · You have the rule in words. How do you get from the sentence to the check — and how do you know the check says exactly what the sentence said?
Rules Come From Examples

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.

Q · You listed the rules you could think of and the list feels thin. Where do the rules you did not think of come from?
Inject a Constraint and Follow It Through
▶ lab

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.

Q · A new rule arrives after the solution works. How do you change the implementation without breaking what it already does — and how do you know you touched everything the rule reaches?
Rules That Live Elsewhere

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.

Q · The cart has five rules. Which of them are the cart's to enforce, which belong to another component, and what happens when the cart enforces one that is not its own?