Edexcel International Advanced Level Computer Science, point 9.2.3
Controlling behaviour means making sure code does the right thing, including with unusual or bad input, and stays simple enough to follow. The specification refers to the PLS and the Good Programming Practice Guide (GPPG) for detail.
a. Boundary value analysis
Boundary value analysis is testing (and designing) around the edges of valid ranges, because errors are most likely there.
For a valid range from 1 to 10, test the boundary values and the values just either side:
| Value | Type | Expected |
|---|---|---|
| 0 | just below the lower boundary | Reject |
| 1 | lower boundary | Accept |
| 2 | just above | Accept |
| 9 | just below the upper boundary | Accept |
| 10 | upper boundary | Accept |
| 11 | just above the upper boundary | Reject |
Typical mistakes it finds: using < instead of <=, an off-by-one error in a loop, and range(1, 10) that stops at 9.
def valid_rating(n):
return 1 <= n <= 10
for test in [0, 1, 2, 9, 10, 11]:
print(test, valid_rating(test))
b. Exception handling
Catch errors that happen while the program runs, and respond sensibly instead of crashing (7.1.1).
def get_item(items, index):
try:
return items[index]
except IndexError:
return None # a safe fallback instead of a crash
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
- Catch specific exceptions (
ValueError), not a bareexcept:. - Give a useful message or a safe fallback.
- Use
finallyto tidy up (close files). - Don't use exceptions for normal logic that a simple
ifcan handle.
c. Minimising nested conditionals
Deeply nested if statements are hard to read and to test.
Nested:
if user_exists:
if password_correct:
if not account_locked:
print("Welcome")
else:
print("Account locked")
else:
print("Wrong password")
else:
print("Unknown user")
Flatter, using elif and combined conditions:
if not user_exists:
print("Unknown user")
elif not password_correct:
print("Wrong password")
elif account_locked:
print("Account locked")
else:
print("Welcome")
Other ways: combine conditions with and/or, move code into a subprogram, or use a dictionary instead of a long chain of if statements.
d. Minimising loops
Avoid unnecessary or deeply nested loops: they are slower and harder to follow.
- Use built-in functions instead of writing your own loop:
sum(marks),max(marks),x in items. - Use a comprehension for a simple transform:
squares = [n * n for n in numbers if n > 0]
- Stop early with
breakorreturnonce you have the answer. - Don't repeat a calculation inside a loop if it doesn't change:
# repeated every pass
for item in items:
if item > sum(items) / len(items):
...
# calculated once
average = sum(items) / len(items)
for item in items:
if item > average:
...
- Use a dictionary or set for look-ups, instead of a loop inside a loop (which takes time proportional to ).
e. Using guard clauses
A guard clause checks for invalid or special cases at the start of a subprogram and exits straight away (return or raise), so the main logic follows without extra nesting.
Without:
def first_word(sentence):
if len(sentence.strip()) > 0:
words = sentence.split()
return words[0]
else:
return ""
With a guard clause:
def first_word(sentence):
if not sentence.strip(): # guard: handle the bad case first
return ""
return sentence.split()[0]
Benefits: less nesting, the special cases are dealt with first, and the main path is clear.
f. Managed conversion of data types
Convert types deliberately and safely, with validation and error handling, instead of hoping the data is right (8.1.1).
def menu_choice(text):
try:
choice = int(text.strip())
except ValueError:
return None # not a whole number
if 1 <= choice <= 4: # check the range after converting
return choice
return None
print(menu_choice(" 3 ")) # 3
print(menu_choice("7")) # None (out of range)
print(menu_choice("two")) # None (not a number)
- Convert as early as possible (as soon as input is read).
- Check the result is in range.
- Be aware of loss:
int(3.9)is 3. - Avoid silent type changes that cause confusing bugs.
Worked example
Task: rewrite this function, which works out a delivery charge in pounds from a parcel's weight in kg, using the methods above.
def delivery_charge(weight, is_member):
if weight >= 0:
if weight < 1:
return 3
else:
if weight >= 20:
if is_member:
return 12
else:
return 15
else:
if is_member:
return 5
else:
return 6
else:
return None
Improved:
def delivery_charge(weight, is_member):
if weight < 0: # guard clause: invalid weight
return None
if weight < 1:
return 3
if weight >= 20:
return 12 if is_member else 15
return 5 if is_member else 6
Boundary tests: weights -0.1, 0, 0.9, 1, 19.9, 20 with is_member both True and False should give None, 3, 3, (5 or 6), (5 or 6), (12 or 15).
- The guard clause removes the outer nesting.
- Early returns remove the
elselevels. - The boundaries (0, 1 and 20) are the test cases most likely to reveal an error.
Exam tip: boundary value analysis means testing on and either side of each boundary. For guard clauses, say they handle special cases first and reduce nesting. Name the exception you would catch and why. Reducing nesting and loops makes code more readable and easier to test.
Check yourself
Which test values would you use for boundary value analysis of a range 18 to 65?
17, 18, 19 and 64, 65, 66 (on and either side of each boundary).
What is a guard clause?
A check at the start of a subprogram that deals with invalid or special cases and exits immediately, so the main logic isn't nested.
Why is deeply nested code hard to test?
Each level of nesting adds more paths through the code, and every path needs its own test, so it is easy to miss one; the conditions are also hard to follow.
Give two ways of minimising loops
Any two of: use built-in functions; use comprehensions; stop early; avoid repeating unchanged calculations; use a dictionary or set for look-ups.