Defensive design & maintainability

Computer Science · Programming fundamentals

Question 1 of 10

0

    Which error message is most helpful to a user who has mistyped a date?

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Defensive design & maintainability explained

    Defensive design means writing programs that expect misuse and unusual input, and that still behave safely when it happens. A user may type letters where a number is needed, leave a field empty, or enter a value that is out of range. Defensive programmers check input with validation routines, handle errors with clear messages, and avoid crashes where possible. Techniques include presence checks, range checks, type checks and length checks. Defensive programmers also think ahead about data the program was never designed to handle, and decide in advance how it will respond, so that a single bad input does not bring the whole program down.

    Maintainability is how easily a program can be understood, corrected and extended later. Maintainable code uses meaningful variable and procedure names, short well-defined procedures, comments that explain why rather than what, and a consistent layout. Testing with normal, boundary and erroneous data helps reveal faults. Programs that are defensive and maintainable are cheaper to repair and safer to change.

    Worked example

    A function calculates the mean of a list of test scores, and it must not crash if the list is empty.

    1. Presence check: if the list has no items, return an error message instead of dividing by zero.
    2. Range check: each mark must be between 0 and 100, so a value of 150 is rejected.
    3. Normal case: the marks 40, 55 and 70 have a sum of 165 and a count of 3, so the mean is 165÷3=55165 \div 3 = 55.

    Without the presence check, an empty list would cause a divide-by-zero error, which is exactly the kind of fault defensive design prevents.

    What you will practise

    66 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • What is the main aim of defensive design in programming?
    • A check that a value lies between a minimum and a maximum allowed value is called a:
    • A check that makes sure a required field has not been left empty is called a:
    • What is the purpose of comments in source code?
    • Which variable name is most maintainable for storing a customer’s age?
    • What is the main benefit of consistent indentation?
    • What does input sanitisation mean?
    • Which check ensures that data has been copied correctly, for example by asking the user to type an email address twice?

    …and 58 more.