SLIDE 1
CSZone.co.uk
Click to reveal · Arrow keys also work
OCR J277 · Component 2 · Topic 2.3.1

Producing Robust Programs
Defensive Design

Input validation · Authentication · Maintainability — anticipating misuse in every program

CSZone OCR GCSE Computer Science J277
Learning Objectives

By the end of this video you will be able to...

Explain what defensive design means — writing programs that anticipate and handle misuse, invalid input, and unexpected behaviour
Name and describe the five types of input validation check: range, type, presence, length, and format
Write OCR ERL pseudocode to validate input using WHILE loops that keep asking until valid data is entered
Implement authentication — a username and password system with a limited number of attempts
Describe three techniques for maintainability: meaningful variable names, comments, and the use of subroutines
⚡ A program that crashes or misbehaves when a user types something unexpected is not finished — it needs defensive design to be production-ready.
Defensive Design

What is defensive design — and why does it matter?

DEFINITION
Defensive design is an approach to programming that anticipates how a program could be misused, how users could enter invalid data, and how unexpected situations could cause the program to fail — and then builds in safeguards to handle all of these cases gracefully.
WITHOUT DEFENSIVE DESIGN — PROBLEMS
ageint(input("Enter age: ")) print("Next year you'll be: " + str(age + 1)) // User types "abc" → CRASH (can't convert "abc" to int) // User types -50 → no error, but wrong result // User types "" → CRASH (empty input)
THREE AREAS OF DEFENSIVE DESIGN
Input validation — checking data entered by the user meets the required criteria before using it
Authentication — verifying who the user is before giving access to the program or data
Maintainability — writing code that other programmers (or future you) can read, understand, and update
ANTICIPATING MISUSE — WHAT COULD GO WRONG?
ScenarioDefensive response
User types a letter where a number is expectedType check
User enters a number outside valid rangeRange check
User presses Enter without typing anythingPresence check
User types a password that is too shortLength check
Unauthorised access attemptAuthentication
⚡ Good programs don't just work when everything goes right — they work when users make mistakes, forget instructions, or try to break the system. That is what defensive design is for.
Input Validation

The five types of validation check

VALIDATION CHECK TYPES — OCR SPEC
CheckWhat it tests
RangeIs the value within an acceptable range of numbers?
TypeIs the data the correct data type (e.g. integer, string)?
PresenceHas the user actually entered something (not left blank)?
LengthIs the string the correct length (min/max characters)?
FormatDoes the data match a specific pattern (e.g. date, postcode)?
VALIDATION ≠ VERIFICATION
Validation checks data is reasonable and in the right format. Verification checks data was entered correctly (e.g. typing a password twice). Validation cannot check whether data is true — it only checks whether it is acceptable.
EXAMPLES OF EACH CHECK
Range Age entered must be between 0 and 120. Score must be 0–100.
Type Quantity field must be a whole number, not a letter or decimal.
Presence Name field must not be empty — user must type something.
Length Password must be at least 8 characters. Username must be 3–20 chars.
Format Date must be DD/MM/YYYY. Postcode must follow UK format.
IN THE EXAM
Questions may ask you to name a suitable validation check for a given scenario, or to write code that implements one. The five check names are the standard OCR spec terms — use the exact names listed here.
Input Validation

Validation in OCR ERL — range and presence checks

THE VALIDATION PATTERN
All validation in OCR ERL follows the same structure: get the input once, then loop with WHILE as long as the data is invalid, asking for it again inside the loop. The loop only exits when valid data has been entered.
RANGE CHECK — AGE 0 TO 120
ageint(input("Enter age (0-120): ")) WHILE age < 0 OR age > 120 DO print("Invalid. Enter 0 to 120.") ageint(input("Enter age (0-120): ")) ENDWHILE print("Age accepted: " + str(age))
PRESENCE CHECK — NAME NOT EMPTY
nameinput("Enter your name: ") WHILE name == "" DO print("Name cannot be empty.") nameinput("Enter your name: ") ENDWHILE print("Hello, " + name)
PYTHON — RANGE AND PRESENCE
# Range check: age = int(input("Enter age (0-120): ")) while age < 0 or age > 120: print("Invalid. Enter 0 to 120.") age = int(input("Enter age (0-120): ")) print("Age accepted: " + str(age)) # Presence check: name = input("Enter your name: ") while name == "": print("Name cannot be empty.") name = input("Enter your name: ")
VALIDATION LOOP — STRUCTURE
Step 1Get initial input once before the loop
Step 2WHILE condition is invalid — loop continues
Step 3Print error message, ask for input again inside loop
Step 4After ENDWHILE — data is guaranteed valid
Input Validation

Length check — and combining validation rules

LENGTH CHECK
A length check validates that a string has a minimum or maximum number of characters. Use string.length in the WHILE condition.
OCR ERL — PASSWORD LENGTH CHECK
passwordinput("Enter password: ") WHILE password.length < 8 DO print("Password must be 8+ characters.") passwordinput("Enter password: ") ENDWHILE print("Password accepted.")
OCR ERL — MIN AND MAX LENGTH
usernameinput("Choose username: ") WHILE username.length < 3 OR username.length > 20 DO print("Username: 3 to 20 characters.") usernameinput("Choose username: ") ENDWHILE
COMBINING MULTIPLE VALIDATION RULES
// Validate: score must be 0-100 AND present scoreStrinput("Enter score (0-100): ") WHILE scoreStr == "" DO print("Cannot be empty.") scoreStrinput("Enter score (0-100): ") ENDWHILE scoreint(scoreStr) WHILE score < 0 OR score > 100 DO print("Score must be 0 to 100.") scoreint(input("Enter score (0-100): ")) ENDWHILE
COMBINING RULES — KEY POINTS
Use OR in the WHILE condition to require all rules to pass — the loop continues if any one rule fails. Run checks in the right order — presence check first, then type conversion, then range check. This prevents errors from converting an empty string to an integer.
Authentication

Authentication — username and password

WHAT IS AUTHENTICATION?
Authentication verifies the identity of a user before allowing access to a program or data. The most common form is a username and password combination. A defensive program limits the number of login attempts to prevent brute-force attacks.
OCR ERL — BASIC LOGIN
storedUser"admin" storedPass"secure123" usernameinput("Username: ") passwordinput("Password: ") IF username == storedUser AND password == storedPass THEN print("Access granted") ELSE print("Access denied") ENDIF
PROBLEM WITH BASIC LOGIN
One failed attempt and the program ends. A malicious user could keep running the program to try unlimited passwords. A defensive design limits attempts.
OCR ERL — LOGIN WITH LIMITED ATTEMPTS
storedUser"admin" storedPass"secure123" attempts0 loggedInFALSE WHILE attempts < 3 AND loggedIn == FALSE DO usernameinput("Username: ") passwordinput("Password: ") IF username == storedUser AND password == storedPass THEN loggedInTRUE ELSE attemptsattempts + 1 print(str(3 - attempts) + " attempt(s) remaining") ENDIF ENDWHILE IF loggedIn THEN print("Access granted") ELSE print("Access denied — account locked") ENDIF
TWO EXIT CONDITIONS
The WHILE loop runs while both conditions are true: attempts < 3 AND loggedIn == FALSE. It exits as soon as either condition becomes false — either the user logs in successfully, or they run out of attempts.
Maintainability

Maintainability — the role of comments

WHAT IS MAINTAINABILITY?
Maintainability means writing code that is easy to read, understand, and modify — by the original programmer returning later, or by another programmer entirely. Good maintainability reduces the time and cost of updating or fixing a program.
COMMENTS
Comments are lines of text that the computer ignores — they exist only to explain the code to human readers. In OCR ERL, comments start with //. In Python, with #.
BAD COMMENTS — JUST REPEAT THE CODE
// Add 1 to count ← useless countcount + 1 // Set total to zero ← useless total0
GOOD COMMENTS — EXPLAIN THE WHY
// Scores array — 0-indexed, max 30 students scores ← [0, 0, 0, 0, 0] // Validation: score must be 0-100 inclusive WHILE score < 0 OR score > 100 DO scoreint(input("Score: ")) ENDWHILE // Divide by count+1 to avoid divide-by-zero avgtotal / (count + 1)
WHAT GOOD COMMENTS DO
Explain why the code does what it does, not what it does. Describe the purpose of a block, important assumptions, or non-obvious design choices. A comment should add information the code itself cannot convey.
WHERE TO USE COMMENTS
At the top of a subroutine (what it does, what parameters mean). Above complex logic. To mark important boundaries like the start of a new section. Not on every single line — over-commenting is as bad as under-commenting.
Maintainability

Maintainability — meaningful names and subroutines

MEANINGFUL VARIABLE NAMES
Using descriptive names for variables, functions, and procedures makes code self-documenting. A reader can understand what the code does without needing comments to explain every line.
POOR NAMES — HARD TO UNDERSTAND
x0 FOR i = 0 TO 4 xx + a[i] NEXT i yx / 5 // What is x? What is a? What is y?
MEANINGFUL NAMES — SELF-DOCUMENTING
totalScore0 FOR i = 0 TO 4 totalScoretotalScore + scores[i] NEXT i averageScoretotalScore / 5 // Purpose is immediately clear
NAMING CONVENTIONS
Use camelCase (totalScore) or snake_case (total_score). Avoid single letters except loop counters (i, j). Avoid abbreviations like tm when totalMarks is clearer.
SUBROUTINES FOR MAINTAINABILITY
Breaking a program into well-named subroutines creates modular code. Each subroutine has a single, clear purpose. This makes programs easier to test, debug, and update — you change one subroutine without affecting others.
WITHOUT SUBROUTINES — ONE LONG BLOCK
// 200-line main program with no structure // Hard to find bugs, hard to update, // impossible to test individual parts
WITH SUBROUTINES — MODULAR STRUCTURE
displayMenu() choicegetValidChoice() processChoice(choice) saveResults() // Each does one thing — easy to test, // easy to update, easy to read
THREE MAINTAINABILITY TECHNIQUES — SUMMARY
Comments — explain purpose, assumptions, and non-obvious logic
Meaningful names — variables, functions, and procedures that describe what they hold or do
Subroutines — modular blocks with a single purpose, reusable and independently testable
Worked Example

Defensive design — a complete defensive program

PROBLEM
Write a defensive OCR ERL program that: authenticates the user (max 3 attempts), then validates a quiz score input (must be 0–10). Output the score if valid, or a locked message if authentication fails.
OCR ERL — AUTHENTICATION SECTION
// --- Authentication --- storedUser"student" storedPass"pass123" attempts0 loggedInFALSE WHILE attempts < 3 AND loggedIn == FALSE DO uinput("Username: ") pinput("Password: ") IF u == storedUser AND p == storedPass THEN loggedInTRUE ELSE attemptsattempts + 1 ENDIF ENDWHILE
OCR ERL — VALIDATION SECTION
IF loggedIn THEN // --- Input validation --- scoreint(input("Enter score (0-10): ")) WHILE score < 0 OR score > 10 DO print("Score must be 0 to 10.") scoreint(input("Enter score (0-10): ")) ENDWHILE print("Your score: " + str(score)) ELSE print("Account locked.") ENDIF
DEFENSIVE FEATURES IN THIS PROGRAM
Authentication — 3-attempt limit with loggedIn flag
Range validation — score checked against 0–10 bounds
Comments — sections labelled for readability
Gating — validation only runs if login succeeds
Exam Practice

Defensive design — exam questions

Question 1 — 1 mark
State what is meant by a presence check.
Answer — Q1
A presence check verifies that the user has actually entered a value — that the field is not empty. It ensures data has been provided before processing begins. (1 mark)
Question 2 — 2 marks
Write OCR ERL pseudocode to validate that a number entered by the user is between 1 and 10 inclusive. The program should keep asking until a valid value is entered.
Answer — Q2
numint(input("Enter 1-10: ")) ← [1] WHILE num < 1 OR num > 10 DO print("Invalid. Enter 1 to 10.") numint(input("Enter 1-10: ")) ← [1] ENDWHILE
Mark 1: initial input + WHILE with correct range condition. Mark 2: error message + repeated input inside the loop.
Question 3 — 4 marks
Write OCR ERL pseudocode for a login system that:
• stores a correct username "quiz" and password "abc123"
• allows up to 3 login attempts
• outputs "Welcome!" if credentials are correct
• outputs "Locked" if all 3 attempts fail
Exam Answers

Question 3 — answer and mark scheme

Q3 MARK SCHEME
storedUser"quiz" storedPass"abc123" attempts0 loggedInFALSE ← [1] WHILE attempts < 3 AND loggedIn == FALSE DO ← [1] uinput("Username: ") pinput("Password: ") IF u == storedUser AND p == storedPass THEN loggedInTRUE ← [1] ELSE attemptsattempts + 1 ENDIF ENDWHILE IF loggedIn THEN print("Welcome!") ELSE print("Locked") ← [1] ENDIF
COMMON MARK LOSSES ON THIS Q
• Using IF instead of WHILE — the program only asks once
• Forgetting the loggedIn flag — only checking attempts count means the loop doesn't stop on a correct login
• Not outputting both outcomes — both "Welcome!" and "Locked" branches are required for full marks
MARKS BREAKDOWN
MarkFor...
[1]Correct stored credentials + attempts=0 + loggedIn=FALSE initialised
[1]WHILE with both conditions: attempts < 3 AND loggedIn == FALSE
[1]Correct IF checking both username AND password, setting loggedIn TRUE
[1]Correct output after loop: "Welcome!" if loggedIn, "Locked" otherwise
VALIDATION CHECK TYPES — QUICK REFERENCE
Range — value in bounds Type — correct data type Presence — not empty Length — string length Format — matches pattern
⚡ Exam tip: in "identify a suitable validation check" questions, re-read the scenario for clues — "between X and Y" → range check. "Cannot be blank" → presence check. "Must be exactly N characters" → length check. "Must be a number" → type check.
Common Mistakes

Common mistakes — avoid these in the exam

MISTAKE 1 — Using IF instead of WHILE for validation
Writing an IF statement to check input. The IF only runs once — if the user enters invalid data, the program either crashes or continues with bad data. Validation requires a loop that keeps asking until valid input is received
✓ Always use WHILE for validation — the loop guarantees the program doesn't continue until valid data is entered
MISTAKE 2 — Forgetting the loggedIn flag in authentication
Using only an attempts counter in the WHILE condition. Without a loggedIn flag, the loop runs the full 3 times even if the correct password is entered first time — the program doesn't exit early on success
✓ WHILE condition needs BOTH: attempts < 3 AND loggedIn == FALSE so success exits immediately
MISTAKE 3 — Confusing validation with verification
Describing verification (e.g. entering a password twice to confirm it) when asked about validation. Validation checks data is reasonable and in the right format. Verification checks data was entered correctly — these are two different techniques
✓ Validation = checking data is acceptable. Verification = checking data was entered as intended (e.g. double entry)
MISTAKE 4 — Not getting input again inside the validation loop
Getting the initial input before the WHILE loop, but then forgetting to re-ask inside the loop body. Without asking again inside the loop, the same invalid value is checked repeatedly and the loop never ends — an infinite loop
✓ The repeated input statement must be inside the WHILE loop body — both the error message AND the new input call
Summary

Key points — 2.3.1

Defensive design means anticipating misuse, invalid input, and unexpected behaviour — and building safeguards in. Three areas: input validation, authentication, and maintainability
Input validation — five types: Range Type Presence Length Format. Always coded as a WHILE loop — ask once before the loop, re-ask inside the loop. The program only continues when valid data is entered
Authentication — verify the user's identity with a username and password. A defensive login limits attempts using a counter and a loggedIn flag in the WHILE condition — exits on success or when attempts run out
Maintainability — three techniques: (1) comments that explain why, not just what. (2) meaningful variable names that make code self-documenting. (3) subroutines that break programs into modular, single-purpose, testable blocks
Validation ≠ Verification — validation checks data is acceptable; verification checks data was entered correctly. An IF statement is not enough for validation — only a WHILE loop guarantees the program waits for valid input
⚡ Next topic: 2.3.2 — Testing. Types of testing, test data, and trace tables.
2.3.1 Complete

Defensive Design
Validation · Authentication · Maintainability

Get the full resource pack at CSZone.co.uk

📄
Marked Worksheet
CSZone.co.uk
Quiz
CSZone.co.uk
📊
Slides
CSZone.co.uk
Next Up
2.3.2 — Testing