Edexcel International Advanced Level Computer Science, point 9.2.2
Readable code is easy for a person to understand: you (in six months), a teammate, or an examiner. Computers don't care how code looks, but programmers spend far more time reading code than writing it. The specification refers to the Good Programming Practice Guide (GPPG).
a. Meaningful identifiers
An identifier is the name of a variable, constant, subprogram or class. A good one says what it holds or does.
| Poor | Better |
|---|---|
x, d, tmp2 |
total_price, days_late, swap_value |
calc() |
calculate_fare() |
flag |
is_logged_in |
lst |
student_names |
data1, data2 |
raw_scores, cleaned_scores |
Guidelines:
- Describe the purpose, not the type (
student_names, notlist1). - Use whole words (
quantity, notqty, unless it is well known). - Booleans read like a question (
has_licence,is_empty). - Subprograms are verbs (
get_mark,show_menu). - Short names are fine for tiny scopes (
iin a short loop,x,yfor coordinates). - Avoid misleading names (a variable
totalthat really holds an average).
b. Informative comments
A comment is text ignored by the computer, written for people: # like this.
Good comments explain WHY (the reason, or an assumption), not what the code obviously does.
# Bad: repeats the code
count = count + 1 # add 1 to count
# Good: explains the reason
count = count + 1 # include the header row in the total
Useful kinds of comment:
- A header (what the program or file does, author, date).
- A docstring for a subprogram (what it does, parameters, return value):
def largest(values):
"""Return the largest item in a non-empty list.
values: a list of numbers. Raises ValueError if it is empty.
"""
if not values:
raise ValueError("values must not be empty")
best = values[0]
for v in values[1:]:
if v > best:
best = v
return best
- Explaining a tricky step or an algorithm ("binary search: halve the range each time").
- Notes on assumptions and limits ("assumes the list is sorted").
TODOmarkers for work still to do.
Don't:
- Comment every line.
- Leave outdated comments (they mislead: update them when the code changes).
- Use comments to excuse confusing code: rewrite it clearly instead.
- Leave old code commented out: delete it (a version control system keeps the history, 6.3.2).
Comment-first coding
You can write the comments first to outline the steps, then fill in the code (10.1.2):
# 1. get the list of marks
# 2. work out the average
# 3. show the grade for that average
c. Named constants
Replace "magic numbers" (unexplained values) with named constants (7.1.2).
# unclear
if speed > 30:
...
km = miles * 1.609
# clear
SPEED_LIMIT = 30
KM_PER_MILE = 1.609
if speed > SPEED_LIMIT:
...
km = miles * KM_PER_MILE
- The name explains the value.
- To change it, you edit it in one place.
- It avoids typing errors.
d. Subprograms
Breaking code into small, well-named subprograms makes it read like a description:
def main():
marks = get_marks()
average = calculate_average(marks)
show_result(average)
main()
Even without reading the details, you understand what the program does. Each subprogram is short and does one thing (9.1.2).
Other aids to readability
- Consistent layout (9.2.1).
- Short lines and shallow nesting (9.2.3).
- Blank lines between logical groups.
- Simple expressions: split a long calculation into steps with named intermediate variables.
# dense
r = (b * b - 4 * a * c) ** 0.5 / (2 * a)
# clearer
discriminant = b * b - 4 * a * c
root = discriminant ** 0.5 / (2 * a)
Worked example
Task: improve the readability of this code.
def f(l):
t = 0
for i in l:
t += i
a = t / len(l)
if a >= 25:
return "Hot"
elif a >= 15:
return "Warm"
else:
return "Cold"
Improved:
HOT = 25
WARM = 15
def describe_day(readings):
"""Return Hot, Warm or Cold for the mean of the temperature readings."""
total = sum(readings)
average = total / len(readings)
if average >= HOT:
return "Hot"
elif average >= WARM:
return "Warm"
return "Cold"
Changes: a descriptive function name, a docstring, meaningful variable names (readings, total, average), named constants for the thresholds, and the built-in sum instead of a manual loop (shorter and clearer).
Exam tip: give specific examples (rename x to total_price; comment why, not what). In your own practical code, use meaningful names and short helpful comments, because they earn marks and help you find errors.
Check yourself
What makes an identifier meaningful?
It describes the purpose of the variable, constant or subprogram, using whole words, so the reader understands it without more explanation.
What should a good comment explain?
Why the code does something (a reason or assumption), not just what it does, as the code already shows that.
When is a very short name, such as i, acceptable?
In a tiny scope where its meaning is obvious, such as the counter of a short loop (or x and y for coordinates).
How do subprograms help readability?
They split the program into small, well-named steps, so the main program reads like a description of what it does.