Defensive design and maintainability
Computer Science · GCSE · The School
Planning for the user who breaks things
DEFENSIVE DESIGN anticipates misuse WHILE a program is being written, not after. A number box will eventually receive letters; a file the program expects will eventually be missing; a network connection will eventually drop mid-transfer. A defensively designed program plans for each of these before a single test is run, rather than reacting once one happens.
Input validation: checking before using a value
A RANGE CHECK rejects a number outside sensible limits — an age of 200. A TYPE CHECK rejects text where a number is expected. A PRESENCE CHECK rejects an empty box. A LENGTH CHECK rejects a password of one character. An input box accepting ages 0–120 should reject "twenty", an empty box, and 121 — all three, without crashing.
Authentication: proving who is asking
AUTHENTICATION checks that a user is who they claim to be, usually with a password. A short, common or reused password defeats the purpose, because guessing it — or finding it leaked from another site — needs no cleverness at all. TWO-FACTOR AUTHENTICATION adds a second, different proof, such as a code sent to a phone, so a stolen password alone is not enough.
Maintainability: written for the next reader
MAINTAINABLE code uses names that say what a variable holds (`ageInYears`, not `x`), comments that explain WHY a choice was made rather than restating what the line obviously does, consistent indentation, and SUB-PROGRAMS that replace five repeated blocks of near-identical code with one function called five times.
The same check, two ways
Weak: `IF age > 0 THEN accept` — accepts 500, accepts a decimal, crashes on text. Defensive: `IF age >= 0 AND age <= 120 AND isInteger(age) THEN accept ELSE print "Enter a whole number 0–120"`. The second version anticipates three specific ways a real user gets it wrong, each checked for on purpose, not discovered by accident later.
Readable code is easier to defend
A colleague reading badly named, uncommented code cannot easily tell whether a defence is missing, because following the logic itself takes most of their effort. Maintainable code is not a separate nicety from defensive design — a reader who can follow the logic quickly is the same reader who notices the one case nobody checked for.