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:
| Area | What it addresses |
|---|---|
| Anticipating misuse | Designing for all realistic input values, not just ideal ones |
| Authentication | Verifying a user's identity before allowing access |
| Input validation | Checking 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:
- What data type is expected?
- What range or set of values is valid?
- What format is required?
- 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 type | What it checks | Example |
|---|---|---|
| Range check | Value falls within acceptable limits | Age must be between 0 and 120 |
| Type check | Data is the correct type | Score must be an integer, not a string |
| Length check | Input meets length requirements | Password must be 8–20 characters |
| Presence check | Field is not empty | Name cannot be blank |
| Format check | Input matches a required pattern | Postcode must match a valid format |
| Lookup check | Value is in an approved list | Answer 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.
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 scoreabovescore = score + 1adds 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.
| Mistake | Correction |
|---|---|
| IF instead of WHILE for validation | Use 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 authentication | Validation = 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
Subroutines and Scope
Testing Programs
Related lessons
7 Slides
7 Slides
7 Slides
6 Slides