Validate everything, then change
Make operations all-or-nothing so failures leave no half-done state.
Half-applied changes
A transfer that debits the sender, then finds the receiver does not exist, has already lost money. A booking that holds seats one by one and fails on the third leaves two held.
Check first, write second
Do every check before the first change: accounts exist, amount is valid, funds cover amount plus fee, every seat is free. Only then write. If any check fails, nothing has changed.
transfer(from: string, to: string, amount: number) {
const src = this.account(from); // throws if unknown
const dst = this.account(to);
if (src.balance < amount) throw new Error("Not enough money");
src.balance -= amount; // only now do we write
dst.balance += amount;
}
Key takeaways
- All checks before any write.
- A failed call must leave state exactly as it was.
- Hidden tests check state after failures.
Hands-on coding exercise
Move money between two accounts. If anything is wrong (unknown account, amount of 0 or less, not enough money), throw and change nothing.
Check everything first, then change both balances.
class Bank {
private readonly balances = new Map<string, number>();
open(id: string, balance: number): void {
this.balances.set(id, balance);
}
balanceOf(id: string): number {
throw new Error("Not implemented");
}
transfer(from: string, to: string, amount: number): void {
throw new Error("Not implemented");
}
}
Run your solution against 4 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- hold(seats) marks seats one by one and throws when one is taken. What is wrong?
- What should a failed withdrawal change?