Intermediate

Defensive Design

AicademyAicademy
·OCR GCSE Computer Science·OCR J277·7 min
2.3.1 Defensive design

What Is Defensive Design?

Defensive design means writing programs that anticipate problems and handle them gracefully, rather than assuming everything will go smoothly. A defensively designed program:

  • Accepts only valid input (and handles invalid input without crashing)
  • Confirms the identity of users before granting access
  • Remains understandable and maintainable over time

OCR J277 identifies three areas of defensive design:

AreaWhat it addresses
Anticipating misuseDesigning for all realistic input values, not just ideal ones
AuthenticationVerifying a user's identity before allowing access
Input validationChecking that data meets defined rules before processing it

Plus one area of maintainability: using sub-programs, naming conventions, indentation, and comments to keep code readable and easy to modify.

A program that crashes or produces wrong output when given unexpected input is not production-ready, even if it works perfectly on ideal data.

Anticipating Misuse

When designing a program, consider every realistic way a user might provide unexpected input:

  • Entering a string where a number is expected (e.g. typing "hello" in an age field)
  • Entering a number outside the valid range (e.g. age = -5, or age = 200)
  • Pressing Enter without typing anything (empty string input)
  • Entering the wrong format (e.g. "31/13/2026" as a date — month 13 does not exist)
  • Deliberate attempts to break the system (e.g. very long inputs, special characters)

Design strategy: for every input, define:

  1. What data type is expected?
  2. What range or set of values is valid?
  3. What format is required?
  4. What should happen when the input is invalid?

Worked example — a quiz program asks for an answer of A, B, C, or D. Without defensive design:

answer = input("Your answer: ")
# program proceeds assuming answer is A, B, C, or D
# but user could type "yes", "42", or leave it blank

With defensive design, the program validates before proceeding.

Input Validation

Input validation checks that data entered by the user meets defined rules before the program processes it. Invalid data is rejected and the user is prompted to re-enter.

Types of validation check:

Validation typeWhat it checksExample
Range checkValue falls within acceptable limitsAge must be between 0 and 120
Type checkData is the correct typeScore must be an integer, not a string
Length checkInput meets length requirementsPassword must be 8–20 characters
Presence checkField is not emptyName cannot be blank
Format checkInput matches a required patternPostcode must match a valid format
Lookup checkValue is in an approved listAnswer must be A, B, C, or D

Worked example — validate a score between 0 and 100:

score = int(input("Enter score (0-100): "))
while score < 0 or score > 100:
    print("Invalid. Score must be between 0 and 100.")
    score = int(input("Enter score (0-100): "))
print("Valid score:", score)

The loop repeats until a valid value is entered. The program cannot proceed with an out-of-range score.

Input Validation in Practice

Worked example — validate that an answer is one of A, B, C, or D:

valid_answers = ["A", "B", "C", "D"]
answer = input("Enter answer (A/B/C/D): ").upper()
while answer not in valid_answers:
    print("Invalid. Please enter A, B, C, or D.")
    answer = input("Enter answer (A/B/C/D): ").upper()

Worked example — validate that a username is not empty and is at most 20 characters:

username = input("Enter username: ")
while len(username) == 0 or len(username) > 20:
    print("Username must be 1–20 characters.")
    username = input("Enter username: ")

Both examples use a WHILE loop: the program repeats the input request until valid data is received. This is the standard validation loop pattern.

Validation does not guarantee the data is meaningful, only that it is acceptable in form. Age = 119 passes a 0–120 range check but may still be implausible for a school context. Deeper plausibility checking is beyond what validation alone can provide.

Studying this for an exam?

Generate a personalised learning path for this subject. Free to get started.

Create a learning path

Authentication

Authentication confirms the identity of a user before granting access to a system or its data. Without authentication, any person could access any account.

The simplest authentication model is a username and password check:

correct_username = "admin"
correct_password = "s3cur3!"

username = input("Username: ")
password = input("Password: ")

if username == correct_username and password == correct_password:
    print("Access granted")
else:
    print("Access denied")

Improved authentication — limit login attempts to three:

attempts = 0
while attempts < 3:
    username = input("Username: ")
    password = input("Password: ")
    if username == correct_username and password == correct_password:
        print("Access granted")
        break
    else:
        attempts = attempts + 1
        print("Incorrect. Attempts remaining:", 3 - attempts)

if attempts == 3:
    print("Account locked.")

(Extra context — brute-force attacks are not required by OCR J277 2.3.1.) Limiting login attempts prevents an attacker from repeatedly guessing passwords. At this level, you only need to know that limiting attempts is a security improvement over a single-attempt check.

Maintainability — Writing Code Others Can Read

A maintainable program is one that other programmers (or your future self) can understand, modify, and extend without introducing new bugs.

OCR J277 identifies four maintainability techniques:

1. Use of sub-programs — break code into named subroutines. Each subroutine has one clear purpose. A 200-line program split into 10 subroutines of 20 lines each is far easier to debug and extend.

2. Naming conventions — use descriptive, consistent names.

# Poor naming
x = int(input(""))
y = x * 0.2

# Clear naming
price = int(input("Enter price in pence: "))
tax = price * 0.2

3. Indentation — consistent indentation shows the structure of nested blocks visually. Python enforces indentation as syntax; other languages use it for readability.

4. Commenting — add a comment only when the why is not obvious from the code itself.

# Limit to 3 attempts to prevent brute-force login attacks
while attempts < 3:

Commenting what the code does is redundant when the code already says it. # add 1 to score above score = score + 1 adds nothing. A comment explaining why a limit of 3 was chosen is valuable.

Common Exam Mistakes

1. Saying validation "prevents all incorrect input"

Validation checks that input is in an acceptable form, not that it is correct or truthful. A user can enter a valid-format age of 150 — validation passes; the value is still implausible.

2. Validation loops that don't re-prompt

A validation check that only tests once (an IF, not a WHILE) rejects bad input once but does not ask for a corrected value. The loop must re-request input until a valid value is received.

3. Authentication stores passwords in plaintext in exams

At OCR GCSE level, exam questions show passwords stored as plaintext strings. In real systems, passwords are hashed — but this is beyond J277 scope.

4. Confusing authentication and validation

Validation checks the format/range of data. Authentication checks the identity of a user. A login form uses both: validation ensures the username field isn't blank; authentication checks whether the credentials match.

MistakeCorrection
IF instead of WHILE for validationUse WHILE — the input request must repeat until valid
"Validation stops users entering wrong data"Validation stops data that fails format/range rules; it can't stop plausible but incorrect data
Confusing validation with authenticationValidation = data rules; authentication = identity check

Generate revision on any topic you study

Type any topic you're studying and Aicademy generates a complete lesson, quiz, and flashcard set — personalised to your level.

Lessons on anything

Structured, level-matched lessons on any topic you study

Practice quizzes

Find out what you actually know before the exam does

Flashcard sets

Lock in key concepts with instant revision cards

Ask Aica

Stuck on something? Get a clear explanation, any time

Prev

Subroutines and Scope

Next

Testing Programs

Related lessons

7 Slides

Lesson

Subroutines and Scope

OCR GCSE Computer Science · OCR J277

2 days ago

7 Slides

Lesson

Testing Programs

OCR GCSE Computer Science · OCR J277

2 days ago

7 Slides

Lesson

Programming Fundamentals

OCR GCSE Computer Science · OCR J277

2 days ago

6 Slides

Lesson

Cyber Security — Threats and Prevention

OCR GCSE Computer Science · OCR J277

1 day ago