Programming for a Hostile World
Real programs face bad inputs and imperfect environments. Defensive programming anticipates these problems so code behaves safely instead of crashing or outputting garbage.
| Term | Definition |
|---|---|
| Input validation | Checking that inputs meet assumptions before use. |
| Assertions | Statements of a condition that must be true (). |
| Failing fast | Detecting errors close to their source to stop propagation. |
Rejecting bad input at the boundary with a clear error prevents silent state corruption deep inside the program.
Contracts and Pitfalls
Functions require clear preconditions (what inputs are needed) and postconditions (what outputs are guaranteed). Handle errors explicitly via exceptions rather than ignoring them.
| Contract Aspect | Purpose |
|---|---|
| Preconditions | Document and enforce valid inputs. |
| Postconditions | Guarantee correct output state. |
Common pitfall: Trusting that inputs will always be valid because "no one would ever pass a negative here." Unvalidated assumptions break production code. Validate at boundaries and fail fast.