Track progress, take quizzes and save notes on this lesson.

Free forever · no card needed

Start free
Intermediate

Defensive Design

2.3.1 Defensive design

Aligned to the OCR J277 specification

Level
Intermediate
Reading time
7 min
Published
11 June 2026
Updated
1 July 2026
On this page
  1. 1.What Is Defensive Design?
  2. 2.Anticipating Misuse
  3. 3.Input Validation
  4. 4.Input Validation in Practice
  5. 5.Authentication
  6. 6.Maintainability — Writing Code Others Can Read
  7. 7.Common Exam Mistakes

Key takeaways

  • Defensive design means writing programs that anticipate problems - accepting only valid input, verifying user identity, and keeping code maintainable.
  • Input validation checks that data meets defined rules (range, type, length, presence, format, or lookup) before the program processes it, using a WHILE loop so invalid input is re-requested.
  • Authentication confirms a user's identity before granting access; limiting login attempts to three is a security improvement over a single attempt.
  • A common mistake: validation only checks that data is in an acceptable form, not that it is correct - age 150 can pass a 0-120 range check.
  • Maintainability techniques include using sub-programs, descriptive naming, consistent indentation, and purposeful comments that explain why, not what.

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.

Something not quite clicking?

Ask Aica to explain any part of this differently. Free, takes 30 seconds.

Ask Aica

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

Key terms

Defensive design
An approach to writing programs that anticipates problems such as invalid input or unauthorised access, and handles them without crashing.
Input validation
Checking that data entered by a user meets defined rules before the program processes it. Invalid data is rejected and the user is re-prompted.
Range check
A validation check that ensures a value falls within acceptable limits, for example that an age is between 0 and 120.
Type check
A validation check that confirms data is of the correct type, for example that a score is an integer rather than a string.
Length check
A validation check that ensures input meets length requirements, for example that a password is between 8 and 20 characters.
Presence check
A validation check that confirms a field is not empty.
Format check
A validation check that confirms input matches a required pattern, for example that a postcode is in a valid format.
Lookup check
A validation check that confirms a value appears in an approved list, for example that an answer is A, B, C, or D.
Authentication
The process of confirming a user's identity before granting access to a system, typically using a username and password.
Maintainability
The quality of code that makes it easy for other programmers to understand, modify, and extend without introducing new bugs.

Frequently asked questions

Validation checks that input data meets format or range rules, for example that a score is between 0 and 100. Authentication checks the identity of a user by verifying credentials such as a username and password.

An IF statement checks the condition only once and rejects bad input without asking again. A WHILE loop repeats the input request until valid data is entered, which is the required behaviour for input validation.

The four techniques are: use of sub-programs to break code into named, single-purpose routines; descriptive naming conventions; consistent indentation to show block structure; and comments that explain why something is done rather than restating what the code does.

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 min

8 min

Lesson

Testing Programs

OCR GCSE Computer Science · OCR J277

1 month ago

6 min

Top students don’t revise more. They revise what counts.

Start revising free

Free to start. No card needed.