Edexcel International Advanced Level Computer Science, point 19.2.2
Readable code is easy for another person (or you, later) to understand. The ideas are in 9.2.2. In larger Unit 4 programs, readability is what keeps the code manageable. The specification refers to the Good Programming Practice Guide (GPPG).
a. Meaningful identifiers
A name should say what the thing is or does.
| Poor | Better |
|---|---|
d, x2, tmp |
days_late, unit_price, swap_value |
process() |
calculate_overdue_fines() |
flag |
is_member |
data |
student_marks |
l (lower-case L) |
items |
Rules: whole words, nouns for data, verbs for actions, booleans as questions, no single letters except tiny loop counters (i) or well-known maths (x, y), and no misleading names (total holding an average).
b. Informative comments
Comments explain why, not what.
# Poor: repeats the code
i = i + 1 # add one to i
# Good: gives the reason
# count this attempt towards the 3-try limit
retries += 1
Docstrings
Describe each subprogram's purpose, parameters, return value and any preconditions (2.1.2 in other courses, 9.3.1):
def fine_due(days_late, rate_pence=10):
"""Return the fine in pence for a late book.
days_late: whole days after the due date (0 or more).
rate_pence: fine per day in pence.
Returns 0 if the book is not late.
"""
return max(0, days_late) * rate_pence
Other helpful comments
- A short header at the top of each file (what it does).
- An explanation of a tricky step or algorithm.
- Assumptions and limits (
# assumes the list is sorted). TODOmarkers for unfinished work.- References to the source of an algorithm or formula.
Avoid: commenting every line, outdated comments (update them with the code), commented-out old code (delete it; version control keeps it, 6.3.2), and comments used to excuse unclear code (rewrite the code).
c. Named constants
Replace "magic numbers" and repeated literals with named constants.
# unclear
if age >= 17 and mark > 59.5:
...
# clear
MIN_AGE = 17
DISTINCTION_MARK = 60
if age >= MIN_AGE and mark >= DISTINCTION_MARK:
...
Benefits: self-explaining, one place to change, fewer typing slips. Group related constants at the top of a file or in a small module (settings.py).
d. Subprograms
Small, well-named subprograms make the main flow read like a description:
def main():
orders = load_orders()
valid = remove_invalid(orders)
totals = calculate_totals(valid)
print_report(totals)
Even without reading the detail, you know what the program does. Aim for subprograms that fit on one screen and have one job.
Other aids
- Break complex expressions into steps with named variables:
# dense
r = (-b + (b * b - 4 * a * c) ** 0.5) / (2 * a)
# readable
discriminant = b * b - 4 * a * c
root = (-b + discriminant ** 0.5) / (2 * a)
- Use blank lines to separate logical sections.
- Prefer simple, direct logic over clever one-liners.
- Use language features that explain intent (
enumerate,zip,with, comprehensions).
Worked example
Task: rewrite this to be readable.
def f(a, b):
r = 0
for i in a:
if i[1] > b:
r += i[1] * 0.9
else:
r += i[1]
return r
Improved:
BULK_THRESHOLD = 100
BULK_DISCOUNT = 0.10
def total_after_discount(orders, threshold=BULK_THRESHOLD):
"""Return the total of the order values.
orders: list of (customer, value) pairs.
Orders worth more than threshold get a 10% discount.
"""
total = 0
for customer, value in orders:
if value > threshold:
total += value * (1 - BULK_DISCOUNT)
else:
total += value
return total
print(total_after_discount([("Amy", 50), ("Raj", 200)])) # 230.0
Changes: a descriptive function name, a docstring, meaningful names (orders, value, total), named constants for 100 and 0.9, and tuple unpacking in place of i[1]. The behaviour is the same.
Exam tip: give specific before-and-after examples (x becomes total_price; 0.2 becomes VAT_RATE). Comments say why. Practise writing a docstring for each subprogram you write in the exam.
Check yourself
What makes a comment informative?
It explains why the code does something (a reason, assumption or tricky step), instead of repeating what the code obviously does.
What is a docstring?
A string at the start of a subprogram, module or class that describes its purpose, parameters and return value.
Why use a named constant?
It explains the meaning of a value, it can be changed in one place, and it avoids typing mistakes.
How do subprograms improve readability?
They break the program into small, well-named steps, so the main program reads like a description of what it does.