Lesson OCR J277

Producing Robust Programs

Defensive Design, Validation & Maintainability in Python

By the end of this lesson, you will:

1

The "Unmaintainable" Code

Look at the Python code below. It works, but it is terrible. Can you figure out what it does and why it's bad?

a = 3.142 b = int(input("? ")) c = b * b * a print(c)

Why it's bad:

  • Variables a, b, c are meaningless (what do they store?).
  • No comments explaining the formula.
  • The input prompt "?" is confusing for the user.
  • It uses a "Hard-coded Value" (3.142) instead of a Constant. This is often called a "Magic Number".

The "Robust" Version:

# Calculate Area of a Circle CONST_PI = 3.142 radius = int(input("Enter radius: ")) area = radius * radius * CONST_PI print("The area is", area)
2

Maintainability Theory

Comments

Always write comments to explain complex logic. This is for other programmers (or future you) to understand the code.

Meaningful Identifiers

Use variable names that describe the data. Use total_score, never just x.

Sub-programs

Break code into functions (def in Python). This makes it modular and easier to test.

EXAM TIP
Constants

Python doesn't rigidly enforce constants, so use ALL CAPS (e.g., VAT_RATE = 0.2) to tell others "Do not change this". Avoid "Hard-coded values".

3

Defensive Design: Sanitisation

What is Sanitisation?

Many students confuse validation with sanitisation.
Validation checks if data is sensible (e.g., "Is it 8 chars long?").
Sanitisation cleans the data before processing (e.g., "Remove spaces").

Python Task 1: Sanitisation

Copy this code into your Python editor. It "cleans" a username input by removing banned characters like ; (which hackers use for SQL injection) and spaces.

username = input("Enter username: ") # Sanitisation: Remove dangerous characters username = username.strip() # Removes spaces at start/end username = username.replace(";", "") # Prevents SQL injection print("Cleaned username:", username)
4

Theory: Input Validation

Input Validation is checking that data meets a set of rules before the program processes it. It checks if the data is sensible, not necessarily if it's true.

Range Check

Checks if data is within a minimum and maximum limit.

Example: Age between 18 and 100.

Length Check

Checks if data has the correct number of characters.

Example: Password must be 8+ chars.

Presence Check

Checks that data has been entered and is not empty.

Example: Required fields on a form.

Lookup Check

Checks against a list of allowed values.

Example: "M", "F", or "Other".

Format Check

Checks if data follows a specific pattern.

Example: Postcode LL9 9LL.

Type Check

Checks data is the correct type (Integer, Boolean etc).

Example: Entering 'Five' instead of 5.

5

Main Challenge: Club Entry System

Your Task

Write a Python program for a nightclub entry system. It needs to ask for 3 things and validate them:

  1. Name (Must not be empty)
  2. Age (Must be 18 to 30)
  3. Gender (Must be 'M' or 'F')

Use the "Cheat Sheet" on the right to help you write the checks.

Python Validation Cheat Sheet
// 1. Range Check while age < 18 or age > 30:
  print("Invalid age")
  age = int(input("Age: "))
// 2. Length Check if len(password) < 8:
  print("Too short")
// 3. Presence Check while name == "":
  print("Required")
  name = input("Name: ")
// 4. Lookup Check while gender not in ["M", "F"]:
  print("Invalid")
  gender = input("M/F: ")
6

The "Exam Trap" Quiz

Test your knowledge of the tricky concepts found in the mark scheme.

1. The exam question shows a `while` loop that is perfectly indented. You are asked to improve maintainability. What do you suggest?

2. A random number generator picks a number between 1 and 10. Should you write code to validate this number?

3. We check if a password entered matches the one stored in the database. Is this Validation?