Defensive programming is the practice of writing code that protects itself against bad inputs, unexpected conditions, and user mistakes. Rather than assuming everything will go right, a defensive programmer builds in checks so the program handles problems gracefully — staying correct and stable even when the real world is messy.

Why is defensive programming important at GCSE?

Imagine handing an airport check-in program to a traveller. They might type their age as "twenty-three" instead of 23, leave a field blank, or deliberately enter a command hoping to crash the system. A naive program that trusts all input will fail. A defensive program anticipates these scenarios and responds with clear error messages rather than cryptic crashes.

AQA and OCR both name defensive programming as an explicit topic in their GCSE Computer Science specifications. Exam questions ask students to identify which technique a piece of code demonstrates, or to write code that applies a named technique to a given problem.

What is input validation?

Input validation checks that data meets defined rules before the program processes it. If the data fails the check, the program rejects it — usually by asking the user to try again rather than crashing.

Validation checks used at GCSE:

Check type What it tests Example
Range check Is the value between a minimum and maximum? Age between 0 and 120
Type check Is the value the correct data type? Is the input an integer?
Length check Is the string within acceptable length limits? Password 8–20 characters
Presence check Has a required field been filled in? Name field is not empty
Format check Does the value match a required pattern? Date in DD/MM/YYYY format

Worked example — range check in Python:

age = int(input("Enter your age: "))
while age < 0 or age > 120:
    print("Invalid age. Please enter a value between 0 and 120.")
    age = int(input("Enter your age: "))
print("Age accepted:", age)

This loop keeps asking until the user provides a value within the valid range.

What is input sanitisation?

Sanitisation cleans input by removing or escaping characters that could cause harm. It is closely related to validation but focuses on stripping dangerous content rather than rejecting data outright.

A classic example is removing HTML or SQL characters from a text field on a website. If a user types <script>alert('hacked')</script> into a name field, sanitisation converts the angle brackets to harmless text so the script never executes. This prevents injection attacks — a major category of real-world cybersecurity threats.

At GCSE, you are expected to know the difference:

  • Validation checks whether data is acceptable (type, range, format).
  • Sanitisation cleans data to remove potentially harmful content.

What is authentication in defensive programming?

Authentication verifies that a user is who they claim to be before granting access to program features. Common methods include:

  1. Username and password — the most common form. The password is checked against a stored (ideally hashed) value.
  2. Two-factor authentication (2FA) — requires a second piece of evidence such as a code sent to a mobile phone.
  3. Biometrics — fingerprint or facial recognition, used in mobile apps and high-security systems.

At GCSE, defensive programming questions about authentication typically ask students to describe a scenario where authentication is appropriate, or to write a simple password-checking loop.

Example — simple authentication loop:

correct_password = "secure123"
attempts = 0
while attempts < 3:
    entered = input("Enter password: ")
    if entered == correct_password:
        print("Access granted.")
        break
    else:
        attempts += 1
        print("Incorrect. Attempts remaining:", 3 - attempts)
if attempts == 3:
    print("Account locked.")

What does maintaining code mean in defensive programming?

Maintenance-friendly code is a key aspect of defensive design. Techniques include:

  • Meaningful variable namestotal_price is easier to maintain than tp or x.
  • Comments and docstrings — brief explanations of what each section does, so a future programmer (or you, six months later) can understand it quickly.
  • Indentation and consistent formatting — Python enforces indentation, but other languages do not; consistent style aids readability.
  • Modular structure (subroutines) — breaking code into named functions makes each part independently testable and reusable.

Exam questions on code maintenance often ask students to add appropriate comments to a given piece of code, or to rename poorly named variables.

How do you combine defensive techniques in a program?

A robust program applies several techniques together. Consider a student-grade entry system:

  1. Validation: check that the grade is an integer between 0 and 100.
  2. Sanitisation: strip any whitespace the user accidentally typed before or after the number.
  3. Authentication: only a teacher (verified by login) can enter or edit grades.
  4. Meaningful names and comments: make the code easy for another teacher-coder to audit.

Frequently asked questions

What is the difference between validation and verification in defensive programming?

Validation checks that data is sensible and meets defined rules (e.g. age is between 0 and 120). Verification checks that data has been entered correctly — typically by asking the user to type it twice and comparing the two entries (e.g. confirming a new password). Both are defensive techniques, but they guard against different problems: validation guards against impossible values; verification guards against transcription errors.

Do I need to know sanitisation for GCSE Computer Science?

Yes — both AQA and OCR name sanitisation as part of defensive design. At GCSE level, you are expected to explain what sanitisation means (removing or escaping harmful characters) and why it matters (prevents injection attacks). You do not need to implement a full HTML or SQL sanitisation library, but you should be able to describe the concept and give a simple example.

How many attempts should an authentication system allow?

There is no single correct answer, but a common design is three attempts before locking the account (as shown in the example above). Fewer attempts improve security but frustrate legitimate users; more attempts give attackers more chances to guess. At GCSE, any answer that justifies the choice with a clear trade-off will earn marks.

Is defensive programming only relevant to professional developers?

No. Defensive programming is part of the GCSE Computer Science specification because it teaches habits that prevent bugs and security flaws from the very start. Even simple school programs benefit from validation loops — for example, ensuring a quiz program cannot crash if a user types a letter instead of a number for an answer. The principles are the same whether you are writing a school project or a commercial banking application.


For Socratic GCSE Computer Science coaching on defensive programming, testing, and programming techniques, visit aitutors.me.