Menu

Defensive Design

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.

Defensive design considerations

  • Anticipating misuse – planning safeguards for unintended uses.
  • Authentication – confirming who a user is before they reach the program or its data.
  • Input validation – checking that input is sensible before it is used.
  • Maintainability – keeping code easy to read, fix and update.

Anticipating misuse

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.

Without defensive design

Unexpected useUnhandledHandled defensively
Typing a word where a number is neededThe program may crash with a run-time errorA clear message explains what to type and asks again
Pressing Enter with no inputA blank value is storedThe user is told a value is needed
Typing 9000 for a quantityNonsense totals come from invalid dataThe 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.

Practise this