26

Introduce Assertion


Goal

Invariants the code assumes are stated explicitly; readers don't need to deduce them.

Before the refactoring
// rate must be positive
const tax = base * rate;
After the refactoring
if (rate <= 0) throw new Error('rate must be positive');
const tax = base * rate;
Savings

Bugs that violate the invariant fail loudly at the source instead of bubbling out as mysterious downstream errors.

Note

Assertions used as control flow couple production behavior to debug-mode invariants — keep them as runtime contracts that should never fire.