Defensive Design

If you build a bridge, you must ensure it does not collapse when a heavy truck drives over it. Anticipating Misuse ensures your code does not crash when users do silly things.

"Input Sanitisation" (cleaning data) has been removed from the OCR J277 syllabus! Focus ONLY on Validation.

The Defences

Authentication

Verifying identity before granting access to a system. The classic example in an exam is creating a routine that checks a username and password.

pass = input("Enter password: ")
IF pass == "Secret123" THEN
   print("Access Granted")
ELSE
   print("Access Denied")

Input Validation

You cannot trust users. Validation means checking data against limits (e.g. Length checks, Range checks, Presence checks) before accepting it.

  • Range Check: Age must be 1-100.
  • Length Check: Password > 8 chars.
  • Presence Check: Field cannot be blank.
  • Format Check: Email must contain '@'.

Examiner's Eye - The 'IF' Statement Trap

If an exam asks you to validate an input (e.g. asking for an age under 100), DO NOT just use an IF statement! If a user gets it wrong, an IF statement only asks them to try again once. If they get it wrong a second time, the code continues and breaks. To achieve full marks, you MUST use a WHILE loop to permanently trap them until they enter valid data.

The Validation Loop Gateway

Below is a 'While Loop' trapping mechanism. Your task is to set a User ID between 100 and 999. See how the WHILE loop relentlessly denies invalid ranges until the condition is met.

> Booting Validation Protocol...
> Requirements: Integer between 100 and 999.
> Requesting input...
userID = input()
WHILE (userID < 100) OR (userID > 999):
   print("Invalid!")
   userID = input()
print("Saved!")

Check Your Understanding

1. What is the fundamental difference between Authentication and Validation?

2. An algorithm needs to ensure a user enters a password longer than 8 characters. Which control structure MUST be used to ensure the user cannot proceed until they comply?

Written Exam Scenario (AO2/AO3)

Stretch (Grade 9)

"Write a robust algorithm using pseudocode or Python that asks for a 4-digit PIN. The code must check that the PIN is not exactly '1234'. It must use a validation loop to repeatedly reject the user and ask them again until they provide a different, valid PIN. Include briefly commented code." (6 marks)