Edexcel International Advanced Level Computer Science, point 19.1.2
The principles are explained in 9.1.2. For the Unit 4 practical exam, you must apply them to larger problems. This page shows a tangled program, then a cleaner design. The specification points to the Good Programming Practice Guide (GPPG).
The six principles in brief
| Principle | In practice |
|---|---|
| Modularity | Small subprograms and modules, each with one job |
| Separation of concerns | Input, processing, output and storage in different subprograms |
| Minimisation of side effects | Pass data in as parameters and return results; avoid changing globals |
| Scope isolation | Keep variables local; constants may be global |
| Fitness for purpose of input and output | Clear prompts, validation, formatted output |
| Efficiency (time and memory) | A suitable algorithm and structure; no wasted repetition |
A tangled program
total = 0 # global state
def process():
global total
while True:
s = input("price: ")
if s == "q":
break
total = total + float(s) * 1.2
print("Total", total)
process()
Problems:
- Input, calculation and output are mixed in one function.
- A global
totalis changed (a side effect), so it can't be reused or tested. float(s)crashes on bad input (no validation), and the delivery charge rate is a magic number.- Output isn't formatted (
Total 29.400000000000002). - It can't be tested without typing input.
A well-designed version
DELIVERY_RATE = 0.08
def read_price(prompt="Price (q to finish): "):
"""Ask for a price. Return a float, or None to stop."""
while True:
text = input(prompt).strip().lower()
if text == "q":
return None
try:
price = float(text)
except ValueError:
print("Enter a number or q")
continue
if price < 0:
print("Price can't be negative")
continue
return price
def read_prices():
prices = []
while (price := read_price()) is not None:
prices.append(price)
return prices
def total_with_delivery(prices, rate=DELIVERY_RATE):
return sum(prices) * (1 + rate)
def show_total(total):
print(f"Total including delivery: £{total:.2f}")
def main():
show_total(total_with_delivery(read_prices()))
What each principle gave:
| Principle | Where |
|---|---|
| Modularity | Five small subprograms |
| Separation of concerns | read_price/read_prices (input), total_with_delivery (processing), show_total (output) |
| No side effects | total_with_delivery takes a list and returns a number, changing nothing else |
| Scope isolation | No globals except the constant DELIVERY_RATE |
| Fit input and output | A clear prompt, validation, £ and 2 decimal places |
| Efficiency | One pass over the data, sum() is built in |
Testing the logic alone:
print(round(total_with_delivery([10.0, 20.0]), 2)) # 32.4
print(round(total_with_delivery([]), 2)) # 0.0
print(round(total_with_delivery([100], rate=0.05), 2)) # 105.0
This is possible only because the logic is separate from the input. The input could later come from a file or a GUI with no change to the calculation.
Efficiency in a larger program
| Problem | Better design |
|---|---|
Repeated look-ups in a list (x in big_list) inside a loop |
Use a set or dictionary ( look-ups) |
| Recalculating the same value | Calculate once, store in a variable |
| Loading a huge file into memory | Read line by line |
Building a long string with + in a loop |
Collect pieces in a list and "".join(...) |
| A slow sort used on big data | Use sorted() or a better algorithm (15.2) |
# slow: a list membership test inside a loop is O(n) each time
# fine for 3 items, slow for 300 000
banned = ["spam", "scam", "fake"]
# better for large data: a set
banned = {"spam", "scam", "fake"}
Worked example
Task: this function reads marks from the user, works out the grade, and prints it, all in one place. Redesign it using the principles.
def do_marks():
m = int(input("mark"))
if m >= 70: print("A")
elif m >= 50: print("B")
else: print("C")
Redesigned:
GRADE_BOUNDARIES = ((70, "A"), (50, "B"))
def get_mark():
while True:
try:
mark = int(input("Mark (0-100): "))
except ValueError:
print("Enter a whole number")
continue
if 0 <= mark <= 100:
return mark
print("Must be between 0 and 100")
def grade_for(mark):
for boundary, grade in GRADE_BOUNDARIES:
if mark >= boundary:
return grade
return "C"
def show_grade(mark, grade):
print(f"{mark} is grade {grade}")
Why it's better: grade_for(70), grade_for(50) and grade_for(49) can be tested directly (the boundaries), the boundaries are named data (easy to change), input is validated, and output is separate.
Exam tip: name the principle and show where it appears in your code. Pass data in and return results instead of using globals. Keep input and output out of calculation subprograms, so they can be tested.
Check yourself
What is separation of concerns?
Keeping different responsibilities, such as input, processing, output and storage, in different subprograms.
Why is a function that changes a global variable harder to test?
Its result depends on hidden state outside it, so it can behave differently each time and can't be tested in isolation.
Give two ways of improving efficiency in a larger program
Any two of: use a set or dictionary for look-ups; avoid recalculating values; read files line by line; use a better algorithm.
What makes input fit for purpose?
A clear prompt, validation of type and range, and asking again when the data is invalid.