Edexcel International Advanced Level Computer Science, point 9.1.2
These are design principles that make programs reliable, understandable and easy to change. The specification points to the Good Programming Practice Guide (GPPG), which isn't reproduced here.
a. Modularity
Divide the program into separate, self-contained modules (subprograms and files), each with one clear job and a clear interface (its parameters and return value).
- Benefits: easier to understand, test and reuse, and teams can work in parallel.
- How: write subprograms, and group related ones in files (modules) (9.1.3).
b. Separation of concerns
Keep different responsibilities in different parts of the program, so that each part deals with only one concern.
A typical split:
| Concern | Job | Example function |
|---|---|---|
| Input | Get and validate data | get_age() |
| Processing (logic) | Calculate results | is_adult(age) |
| Output | Display results | show_message(text) |
| Data storage | Read and write files or a database | save_scores() |
Poor (everything mixed):
def process():
age = int(input("Age: "))
if age >= 18:
print("Adult")
else:
print("Minor")
Better (separated):
def get_age():
return int(input("Age: "))
def is_adult(age):
return age >= 18
def show_status(adult):
print("Adult" if adult else "Minor")
show_status(is_adult(get_age()))
Why it helps: is_adult can be tested without typing input, the interface can change (a GUI instead of print) without touching the logic, and the logic can be reused.
c. Minimisation of side effects
A side effect is a change that a subprogram makes outside itself: changing a global variable, modifying its argument, or printing or writing a file when you only expected a calculation.
- Side effects make code hard to predict and test, because the result depends on hidden state.
- Good practice: pass data in through parameters and return results, so that a function is predictable: the same inputs always give the same output.
With a side effect:
visits = 0
def record_visit():
global visits
visits = visits + 1 # changes a global
Without:
def next_count(visits):
return visits + 1
visits = next_count(visits)
(Sometimes a side effect is the purpose (a procedure that saves a file). Make it obvious from the name, such as save_scores.)
d. Scope isolation
Keep variables as local as possible, so that code can only use and change what it needs.
- Prefer local variables and parameters to globals (7.1.2).
- A local variable can't be changed by other subprograms, so bugs are easier to track.
- The same name can be used in different subprograms without a clash.
- Constants may be global, because they don't change.
e. Fitness for purpose of input and output
Inputs and outputs should suit the user and the task.
Input:
- Clear prompts that say what to enter and in what format (
"Enter date (DD/MM/YYYY): "). - Validation: check type, range, length, format and presence, and ask again if wrong.
- Sensible defaults and choices (a menu or a list) to reduce mistakes.
def get_choice():
while True:
answer = input("Choose A, B or C: ").strip().upper()
if answer in ("A", "B", "C"):
return answer
print("Please type A, B or C")
Output:
- Clear, labelled and formatted results (
"Total: £12.50"). - Helpful error messages that say what went wrong and what to do.
- Appropriate to the audience (a total, not a debug dump).
f. Efficient solutions in terms of execution time and memory usage
Choose methods that don't waste time or memory, without making the code hard to read.
| Aim | Practices |
|---|---|
| Faster | A better algorithm (binary search on sorted data instead of linear search), fewer or simpler loops, don't repeat the same calculation (store it in a variable), stop early when you have the answer (break, return) |
| Less memory | Don't keep unneeded copies of large data, read a file line by line instead of loading all of it, use the right structure (a set for membership) |
# repeated work
for i in range(len(items)):
if len(items) > 10: # len() worked out every time
...
# better
count = len(items)
for i in range(count):
if count > 10:
...
Balance: correct and readable first, then efficient where it matters. Premature optimisation can make code harder to understand.
Worked example
Task: a quiz program asks questions, checks the answers and prints the score, but everything is in one function that adds to a global score. Describe four improvements using these principles.
- Separation of concerns: split into
ask_question()(input),check_answer(given, correct)(logic) andshow_score(score, total)(output). - Minimise side effects:
check_answerreturns True or False instead of adding to the global score itself. - Scope isolation:
scoreis a local variable in the main loop, so no subprogram can change it by accident. - Fit for purpose: answers are cleaned (spaces removed, case ignored) before checking, and the score is shown with a label.
def ask_question(question):
return input(question + " ")
def check_answer(given, correct):
return given.strip().lower() == correct.strip().lower()
def show_score(score, total):
print(f"Score: {score} out of {total}")
questions = [("Capital of France?", "Paris"), ("5 x 6?", "30")]
score = 0 # local to the main program
for question, correct in questions:
if check_answer(ask_question(question), correct):
score = score + 1
show_score(score, len(questions))
Result: the logic can be tested alone (check_answer(" paris", "Paris") should be True), and the interface can change (buttons instead of typing) without altering the checking.
Exam tip: name the principle and say how it helps ("separating input, processing and output means the logic can be tested without typing data"). For side effects, mention globals and changed arguments. For efficiency, give a specific change (stop early, avoid repeated calculations).
Check yourself
What is separation of concerns?
Keeping different responsibilities, such as input, processing, output and storage, in different parts of the program.
What is a side effect?
A change a subprogram makes outside itself, such as altering a global variable or its argument.
Why prefer local variables to global variables?
Other code can't change them accidentally, so bugs are easier to find, and subprograms are more reusable.
Give two ways to make a program's input fit for purpose
Any two of: clear prompts; validation of type, range and format; asking again on invalid data; offering menus or defaults.
Give one way to make code more efficient in time
Any one of: use a better algorithm; avoid repeating calculations; reduce unnecessary loops; stop early when the result is found.