Edexcel International Advanced Level Computer Science, point 19.2.3
The six methods are explained in 9.2.3. For Unit 4, you must select and apply them in larger programs, often by improving code you are given. The specification points to the PLS and the Good Programming Practice Guide (GPPG).
The six methods
| Method | Aim |
|---|---|
| a. Boundary value analysis | Test and design for the edges of valid ranges |
| b. Exception handling | Catch run-time errors and respond sensibly |
| c. Minimising nested conditionals | Flat, readable decisions |
| d. Minimising loops | Fewer, simpler loops; built-ins and comprehensions |
| e. Using guard clauses | Deal with bad or special cases first and leave early |
| f. Managed conversion of data types | Convert deliberately, with validation and error handling |
A tangled routine
A function receives an order as a dictionary. It must check the quantity (1 to 99) and the unit price (above 0), then return the cost with a 5% discount for 10 or more items, and None if anything is invalid.
def order_cost(order):
if "qty" in order and "price" in order:
try:
q = int(order["qty"])
p = float(order["price"])
if q >= 1:
if q <= 99:
if p > 0:
if q >= 10:
return q * p * 0.95
else:
return q * p
else:
return None
else:
return None
else:
return None
except:
return None
else:
return None
Problems: six levels of nesting, a bare except: (hides every error), many repeated return None, magic numbers, and the logic is hard to follow and to test.
The improved version
MIN_QTY, MAX_QTY = 1, 99
BULK_QTY = 10
BULK_FACTOR = 0.95
def order_cost(order):
"""Return the cost of an order, or None if it is invalid."""
# e. guard clause: missing fields
if "qty" not in order or "price" not in order:
return None
# f. managed conversion, b. exception handling (specific exceptions)
try:
quantity = int(order["qty"])
price = float(order["price"])
except (ValueError, TypeError):
return None
# e. guard clauses for each rule, c. no nesting
if not MIN_QTY <= quantity <= MAX_QTY:
return None
if price <= 0:
return None
cost = quantity * price
if quantity >= BULK_QTY:
cost *= BULK_FACTOR
return cost
What changed:
| Method | How it was used |
|---|---|
| e. Guard clauses | Each invalid case returns straight away, so the main path isn't indented |
| c. Minimising nesting | From 6 levels down to 1 |
| b. Exception handling | A narrow except (ValueError, TypeError), not a bare except |
| f. Managed conversion | Conversion is in one place, with failure handled |
| a. Boundary values | The range check MIN_QTY <= quantity <= MAX_QTY has clear boundaries (see the tests) |
| Named constants | No magic numbers |
a. Boundary value analysis in practice
Test on and either side of each limit:
Input (qty, price) |
Expected | Why |
|---|---|---|
0, 5 |
None |
Just below the minimum |
1, 5 |
5.0 |
The minimum |
99, 1 |
94.05 |
The maximum, with the 5% discount |
100, 5 |
None |
Just above the maximum |
9, 10 |
90.0 |
Just below the bulk limit (no discount) |
10, 10 |
95.0 |
The bulk limit (discount applies) |
5, 0 |
None |
The price boundary |
"abc", 5 |
None |
Erroneous type |
| (field missing) | None |
Erroneous data |
tests = [({"qty": 0, "price": 5}, None),
({"qty": 1, "price": 5}, 5.0),
({"qty": 100, "price": 5}, None),
({"qty": 9, "price": 10}, 90.0),
({"qty": 10, "price": 10}, 95.0),
({"qty": "abc", "price": 5}, None),
({"qty": 5}, None)]
for order, expected in tests:
result = order_cost(order)
ok = result == expected or (result is not None
and abs(result - expected) < 1e-9)
print(order, result, "OK" if ok else "FAIL")
d. Minimising loops
Replace a hand-written loop with a built-in or a comprehension when it is clearer:
# a loop
total = 0
for n in numbers:
if n > 0:
total += n
# minimised
total = sum(n for n in numbers if n > 0)
Other ways: any() and all() instead of a flag loop, max/min, in with a set instead of a loop, and leave a loop early with break or return once you have the answer. Avoid a loop inside a loop if a dictionary can do the look-up.
Worked example
Task: apply the methods to this function, which finds the average of a list of marks (0 to 100), ignoring any invalid strings.
def average_marks(items):
total = 0
count = 0
for x in items:
try:
m = int(x)
if m >= 0:
if m <= 100:
total += m
count += 1
except:
pass
if count > 0:
return total / count
else:
return None
Improved:
def to_valid_mark(value):
"""Return the mark as an int, or None if invalid."""
try:
mark = int(value)
except (ValueError, TypeError):
return None
return mark if 0 <= mark <= 100 else None
def average_marks(items):
marks = [m for m in map(to_valid_mark, items) if m is not None]
if not marks: # guard clause
return None
return sum(marks) / len(marks)
print(average_marks(["70", "abc", 85, "101", "-3", 55])) # 70.0
Methods used: managed conversion (to_valid_mark), specific exception handling, a guard clause for an empty result, no nesting, a comprehension in place of a loop and counters. Boundary tests: "0" and "100" are valid, "-1" and "101" aren't.
Exam tip: name the method you've used and what it prevents. Catch specific exceptions. Use guard clauses to flatten nesting. Include boundary values in your test data. Convert types in one place, with try/except.
Check yourself
What is a guard clause?
A check at the start of a subprogram that deals with invalid or special cases and returns immediately, so the main logic isn't nested.
Why is a bare except: a bad idea?
It catches every error, including unexpected ones, which hides bugs.
Which test values check the limits 1 to 99?
0, 1, 2 and 98, 99, 100 (on and either side of each boundary).
Give two ways to minimise loops
Any two of: use built-ins such as sum or max; use comprehensions; use any or all; stop early; use a dictionary or set for look-ups.