🛡️ Component 2 · 2.3 Producing Robust Programs
2.3.1 Defensive Design
OCR J277 · GCSE Computer Science · ~10 min read · Free lesson
Notes
Video
Slides
Worksheet
Quiz

What is Defensive Design?

Defensive design is the practice of writing programs that anticipate and handle invalid input, unexpected usage, and potential misuse — making software more robust and reliable. OCR J277 covers four key aspects:

  • Input validation — checking that user input meets expected criteria before processing
  • Input sanitisation — cleaning/transforming input to make it safe and consistent
  • Anticipating misuse — writing code that handles unexpected situations gracefully
  • Authentication — verifying a user's identity before granting access to a system

Input Validation

Validation checks that input data meets specific rules before the program uses it. If the input fails validation, the user is asked to re-enter data.

Validation TypeDescriptionExample
Range checkChecks value is within an allowed rangeAge must be between 0 and 120
Type checkChecks data is the correct typeInput must be an integer, not a string
Length checkChecks data is within length limitsPassword must be 8–20 characters
Presence checkChecks a required field is not emptyUsername field cannot be blank
Format checkChecks data matches a required patternDate must be DD/MM/YYYY format
Lookup checkChecks value is from a valid setGrade must be A, B, C, D, or E

Validation — Pseudocode Example

// Range check — age must be 0–120
age = int(INPUT)
WHILE age < 0 OR age > 120
    OUTPUT "Invalid age. Please enter a value between 0 and 120."
    age = int(INPUT)
END WHILE
OUTPUT "Age accepted: " + str(age)

// Presence check — username cannot be blank
username = INPUT
WHILE username == ""
    OUTPUT "Username cannot be blank."
    username = INPUT
END WHILE

Input Sanitisation

Sanitisation modifies input data to make it safe or consistent — it goes beyond just checking. It transforms the data before using it.

  • Trimming whitespace — removing leading/trailing spaces: " Alice ""Alice"
  • Changing case — converting to uppercase or lowercase for consistency: "YES""yes"
  • Removing special characters — preventing malicious input (e.g. SQL injection)
  • Converting data type — ensuring input is stored as the right type: "42"42
// Sanitise: lowercase and trim username input
rawInput = INPUT
username = rawInput.lower().strip()  // " Alice " → "alice"

// Sanitise and validate: menu choice must be 1-3
choice = INPUT
choice = choice.strip()  // remove whitespace
WHILE choice != "1" AND choice != "2" AND choice != "3"
    OUTPUT "Please enter 1, 2, or 3."
    choice = INPUT.strip()
END WHILE

Anticipating Misuse

Robust programs handle unexpected situations that a malicious or careless user might cause:

  • Division by zero — check denominator is not zero before dividing
  • Array index out of bounds — check index is within valid range
  • Empty file — check file is not empty before reading
  • SQL injection — sanitise input before using in database queries
  • Overflow — check values don't exceed expected limits
// Anticipating division by zero
divisor = int(INPUT)
IF divisor == 0 THEN
    OUTPUT "Error: Cannot divide by zero."
ELSE
    result = 100 / divisor
    OUTPUT result
END IF

Authentication

Authentication is the process of verifying that a user is who they claim to be before granting access to a system. It is a key layer of defensive design — preventing unauthorised access even when other defences fail.

MethodHow it worksExample
Username & passwordUser enters credentials; system checks against stored (hashed) valuesLogging in to a school VLE
BiometricVerifies a physical characteristic unique to the userFingerprint or face ID on a phone
Two-factor auth (2FA)Combines two methods: something you know + something you havePassword + one-time code sent to phone
CAPTCHADifferentiates between human users and automated bots"I am not a robot" checkbox or image puzzles

Strong passwords are a key defensive measure. Programs should enforce:

  • Minimum and maximum length (e.g. 8–20 characters)
  • A mix of uppercase, lowercase, numbers, and special characters
  • Rejection of easily guessed words or personal information
// Validate password meets length requirement
password = INPUT
WHILE len(password) < 8 OR len(password) > 20
    OUTPUT "Password must be 8–20 characters."
    password = INPUT
END WHILE

Validation vs Sanitisation — Summary

ConceptWhat it doesExample
ValidationChecks if input meets rules — accepts or rejectsAge 150 → rejected
SanitisationTransforms input to make it safe/consistent" Hello " → "hello"
Exam tip: OCR J277 commonly asks: "Give one example of input validation" (give a type + example: range check, type check, length check, presence check, format check, lookup check). Also know the difference between validation (checking/rejecting) and sanitisation (modifying/cleaning). Common 4-mark questions ask you to write a validation loop in pseudocode using WHILE. You may also be asked to "State one method of authentication" — acceptable answers include username and password, biometric (fingerprint/face recognition), or two-factor authentication (2FA).
⚠️ Common Mistakes
  • Confusing validation and sanitisation — validation checks; sanitisation modifies
  • Using IF instead of WHILE for validation — IF only checks once; WHILE keeps asking until valid
  • Forgetting to re-prompt the user inside the validation loop
  • Only naming a validation type without explaining it — always say what it checks
  • Thinking validation prevents ALL errors — it only guards against invalid input, not logic errors
✅ Notes completed!
Video coming soon
Click slide or press arrow keys to navigate

Worksheet — 2.3.1 Defensive Design

8 questions · 24 marks

Q1Define 'defensive design'. Why is it important?[2]
✅ Mark scheme
Defensive design is writing programs that anticipate and handle invalid input, unexpected usage, or misuse [1]. It is important because it makes programs more robust, reliable, and secure — preventing crashes, data corruption, or security vulnerabilities [1].
Q2Name four types of input validation and give one example of each.[4]
✅ Mark scheme
Any 4 from (1 mark each for type + example): Range check — age must be 0–120 [1]; Type check — input must be an integer [1]; Length check — password must be 8–20 chars [1]; Presence check — username cannot be blank [1]; Format check — date must be DD/MM/YYYY [1]; Lookup check — grade must be A, B, C, D, or E [1].
Q3Write OCR J277 pseudocode to validate that a user enters a score between 0 and 100. The program should keep asking until a valid score is entered.[4]
✅ Mark scheme
score = int(INPUT) [1]; WHILE score < 0 OR score > 100 [1]; OUTPUT "Invalid. Enter 0–100." [1]; score = int(INPUT) [1]; END WHILE. Award all 4 for complete correct loop with re-prompt inside.
Q4Explain the difference between input validation and input sanitisation.[2]
✅ Mark scheme
Validation checks if input meets specific rules and accepts or rejects it [1]. Sanitisation modifies/cleans input data to make it safe or consistent (e.g. removing spaces, converting case) without necessarily rejecting it [1].
Q5Give two examples of input sanitisation and explain what each does.[4]
✅ Mark scheme
Any 2 (2 marks each — method + explanation): Trimming whitespace — removes leading/trailing spaces so " Alice " becomes "Alice" [2]; Converting to lowercase — ensures "YES", "Yes", "yes" are all treated the same [2]; Removing special characters — prevents malicious characters (e.g. SQL injection attacks) [2]; Type conversion — converts "42" (string) to 42 (integer) so arithmetic works [2].
Q6Explain what 'anticipating misuse' means in defensive design. Give two examples of how a program might fail without this consideration.[3]
✅ Mark scheme
Anticipating misuse means writing code that handles unexpected or malicious usage gracefully — preventing crashes, incorrect results, or security breaches [1]. Examples (any 2): Division by zero — if divisor is 0 and not checked, program crashes [1]; Array index out of bounds — accessing index 10 in a 5-element array causes a runtime error [1]; SQL injection — unfiltered user input injected into a database query can delete data [1]; Overflow — entering a value too large for the data type causes corruption [1].
Q7A programmer uses IF instead of WHILE for input validation: IF age < 0 OR age > 120 THEN OUTPUT "Invalid" END IF. What is wrong with this approach?[2]
✅ Mark scheme
An IF statement only checks once [1]. If the user enters an invalid value, the message is displayed but the program continues with invalid data. A WHILE loop keeps repeating until valid data is entered [1].
Q8Write OCR J277 pseudocode to ask a user for a password and keep asking until it is at least 8 characters long.[3]
✅ Mark scheme
password = INPUT [1]; WHILE len(password) < 8 or password.length < 8 [1]; OUTPUT "Password too short — must be at least 8 characters."; password = INPUT [1]; END WHILE. Award for initial input, WHILE condition on length, and re-prompt inside loop.
?
out of 24 — self-mark above
Topic Quiz
Question 1 of 15
You scored
out of 15
Card 1 of 10
Click to reveal definition
🎉
Complete!
TermDefinition
🎯

Mini Test — 2.3.1 Defensive Design

10 questions · 10 marks · 10 minutes

← 2.2.1f File Handling 2.3 Robust Programs 2.3.2 Testing →