Quiz Entry - updated: 2026.07.05
What is defensive programming and how does it relate to security?
Write code that assumes inputs are hostile and handles every error — it's the implementation-level form of "never trust user input."
Write code that anticipates misuse and handles it gracefully, rather than assuming correct inputs.
Key practices:
- Validate all inputs — Check type, length, format, range (even from "trusted" sources)
- Never trust external data — User input, API responses, file contents, environment variables
- Check return values — Don't assume operations succeeded
- Use assertions — Verify assumptions about program state
- Handle all error cases — No empty catch blocks
Security connection: Most vulnerabilities exist because code doesn't handle unexpected inputs:
- Buffer overflow → Didn't check input length
- SQL injection → Didn't validate/escape input
- Path traversal → Didn't validate file path
Defensive programming is the implementation-level version of "never trust user input."
Go deeper:
Wikipedia — Defensive programming — anticipating misuse, input canonicalization, and the "all data is tainted" rules.