OCR H446, section 2.1.2 (b)
A precondition is something that must be true before a subroutine or algorithm runs, for it to work correctly. If a precondition isn't met, the result can be wrong, or the program can crash or loop forever.
Examples
| Algorithm or subroutine | Precondition |
|---|---|
| Binary search | The list must be sorted |
sqrt(x) |
x must be zero or more |
divide(a, b) |
b must not be zero |
pop() on a stack |
The stack must not be empty |
dequeue() |
The queue must not be empty |
| Reading a file | The file must exist and be readable |
| Logging in | The user must be registered |
| Withdrawing money | The balance must be enough |
An array index a[i] |
i must be within the bounds of the array |
Why preconditions matter
- They state the conditions the subroutine assumes, so it needn't handle every possible situation.
- They document the contract: the caller must provide the precondition, and the subroutine will then guarantee the result.
- They help find the cause of bugs: if a precondition is broken, the fault is in the calling code, not the subroutine.
- They help with testing, because tests can include cases that meet and break the conditions.
Handling preconditions
There are three common approaches.
1. Check before calling
The caller makes sure the condition holds:
numbers.sort() # make sure the list is sorted first
position = binary_search(numbers, target)
2. Check inside the subroutine
The subroutine tests its own preconditions, and responds if they fail:
def divide(a, b):
if b == 0:
raise ValueError("b must not be zero")
return a / b
An assertion gives a short way to do this during development:
def pop(stack):
assert len(stack) > 0, "stack is empty"
return stack.pop()
3. Document it
State the precondition in a comment or docstring, so other programmers know:
def binary_search(items, target):
"""Return the index of target in items, or -1.
Precondition: items must be sorted in ascending order.
"""
Preconditions and validation
Validation (checking input data) protects the program from bad data typed in by a user. A precondition is about what a subroutine expects from the code that calls it. They are related: validation is often how you make sure a precondition is true before data reaches the subroutine.
Postconditions
A postcondition is what will be true after the subroutine finishes, if the preconditions were met. For binary search: "returns the index of the target, or -1 if it isn't there". Preconditions and postconditions together make up the contract of the subroutine.
Trade-offs
| Checking preconditions | Not checking |
|---|---|
| Safer, catches errors early with a clear message | Faster, less code |
| Costs a little time on each call | Risk of wrong results or crashes if misused |
For code that others will call, checking is usually worth it.
Worked example
Task: state the preconditions for this subroutine, and show what happens when they are broken.
def average(marks):
return sum(marks) / len(marks)
- Preconditions:
marksmust be a list of numbers, and it must contain at least one item. - If broken:
average([])divides by zero and the program crashes withZeroDivisionError.average(["a", "b"])fails because strings can't be added. - Improved version:
def average(marks):
"""Precondition: marks is a non-empty list of numbers."""
if len(marks) == 0:
raise ValueError("marks must not be empty")
return sum(marks) / len(marks)
Now the failure is clear and easy to trace, and the precondition is documented.
Exam tip: a precondition is about what must be true before something runs. The standard example is that binary search needs the data sorted. When asked why a precondition is useful, say that it makes assumptions explicit, prevents errors, and helps programmers use the subroutine correctly. Write each precondition as a specific condition that can be checked, such as "the width is greater than 0" or "the list is sorted", not something vague like "the data is correct".
Check yourself
What is a precondition?
A condition that must be true before a subroutine or algorithm runs, for it to work correctly.
State a precondition of a binary search
The list of data must be sorted.
Give two ways of dealing with a precondition
Any two of: make sure it holds before the call; test it inside the subroutine and give an error if it fails; document it in a comment or docstring.
What is a postcondition?
What will be true after the subroutine has run, provided the preconditions were met.