Money, Quantities, and Domain Invariants
Work through positive and negative transfers with visible balances, then define accepted amount formats, units, and stored outcomes.
You’re reading a preview. Premium includes the full lesson and specialist practice. View the full curriculum.
Mia sends £10 to a friend. Her balance should fall by £10, and the friend's should rise by £10. What if the request supplies −£10 and the code still subtracts it from Mia and adds it to the friend?
| Amount | Sender change | Recipient change |
|---|---|---|
| £10 | −£10 | +£10 |
| −£10 accepted by the same arithmetic | +£10 | −£10 |
The second row reverses the intended transfer. A rule that must stay true—such as "the transfer amount is positive"—is called an invariant.
We'll work through that arithmetic first. Then we'll define the accepted amount format, make the units explicit, and check the stored balance and ledger changes.
Write the transfer invariant before reading syntax
For a simple same-currency no-fee transfer, a successful operation debits a positive amount from an authorized sender, credits the same amount to the permitted recipient, and preserves the combined value. Real products may add fees, holds, exchange rates, limits, and settlement states; include those actual rules rather than assuming the simplified model is universal.
// Unsafe original teaching outline.
const amount = parseFloat(request.body.amount);
if (sender.balance < amount) throw insufficientFunds();
sender.balance -= amount;
recipient.balance += amount;
await saveBoth(sender, recipient);
With amount -20, a balance of 100 is not less than -20. Subtracting -20 produces 120 for the sender; adding -20 reduces the recipient. The check answers whether one comparison succeeds, not whether the transfer represents a permitted movement of money. Authentication can be correct while this value policy fails.
Trace the value through the insufficient-funds check and both updates.
Parse. A permissive parser admits a negative value.
const amount = parseFloat("-20");
Compare. A positive balance is not less than a negative amount.
100 < -20 // false
Apply. Subtracting negative credits the sender and adding negative debits the recipient.
sender = 100 - (-20); // 120
recipient = 50 + (-20); // 30
Review question: A comparison can be syntactically correct while enforcing the wrong domain rule.