Defensive Design
Defensive design is planning and writing a program so it keeps behaving correctly when users do unexpected things, is difficult to misuse and stays easy to maintain. A program built this way is robust. Robustness comes from expecting that some users will act unexpectedly, by accident or on purpose.
Anticipating misuse means thinking ahead about accidental and deliberate uses you did not intend, and building safeguards before anyone runs the program. A programmer must cater for all likely input values, not only the expected ones.
For example, a school library program asks for a book number from a printed list. The expected values are 100 to 199. Likely values also include 99 and 200 from a misread list, 1O5 with a letter O instead of zero, and a blank if Enter is pressed by mistake. Each is a case to plan for.
| Unexpected use | Unhandled | Handled defensively |
|---|---|---|
| Typing a word where a number is needed | The program may crash with a run-time error | A clear message explains what to type and asks again |
| Pressing Enter with no input | A blank value is stored | The user is told a value is needed |
| Typing 9000 for a quantity | Nonsense totals come from invalid data | The value is checked against allowed limits before use |
Unhandled cases can make a program crash, behave incorrectly, store invalid data or reveal data it should keep back.
Defensive design reduces misuse by checking input, limiting login attempts, giving clear error messages and not trusting data just because a user entered it. A helpful message says exactly what went wrong and what to do next, such as “Please type a book number from 100 to 199.” A good program should explain the problem and carry on rather than simply stop with an error.
OCR GCSE Computer Science · Defensive Design