Sub topic 4
Specifying behavior: preconditions, results, and axioms
This chapter assumes you can read Python classes and exceptions, and that you already know an abstract data type (ADT) is defined by its operations rather than by how it stores data. Here you learn how to say precisely what those operations promise. Without that, "the stack works" has no checkable meaning.
Why a signature is not enough
A signature gives names, parameter types, and a return type. For pop(self) it tells you nothing about which item comes back, what happens on an empty stack, or whether the stack changes. Two implementations can share every signature and still behave differently. One might return the oldest item, another the newest.
A behavioral specification fills that gap. It has three parts, and each answers a different question.
| Part | Question it answers | Who is responsible |
|---|---|---|
| Precondition | What must be true when the operation is called? | The caller |
| Result (postcondition) | What is true afterward, and what is returned? | The implementer |
| Axioms | Which facts hold across combinations of operations? | The implementer |
Preconditions
A precondition is a condition on the inputs and the current state that the caller must satisfy. If the caller breaks it, the specification promises nothing. Most real ADTs use two styles for this.
- Partial operation. The precondition is strict, and behavior outside it is undefined. For example, "
poprequires a non-empty stack." - Total operation. The operation is defined for every input, and the bad case has a stated outcome, such as raising an exception or returning a sentinel.
The stack specification from this tutorial's running example takes the second path: "pop() and peek() raise IndexError on an empty stack." The error case is part of the promise. A client can rely on IndexError and write code that catches it. An implementation that returns None instead breaks the contract, even though it never crashes.
Choosing between the two styles is a design decision.
- A partial operation is cheap to implement, because no checks are needed. It is risky when callers are many and unknown.
- A total operation with a defined error is safer, and it gives clients something to test against.
Whichever you choose, write it down. A condition that exists only in the implementer's head is not a precondition.
Results
The result states what the operation returns and how it changes the abstract state. Describe it in terms of the abstract values, not the storage. "Adds x to the set" is a result. "Appends x to the _items list" is an implementation detail, and it would force every future implementation to use a list.
Separate two kinds of effect when you write a result.
- The return value. For example,
size()returns the number of distinct elements. - The change of state. For example, after
add(x),contains(x)is true.
Observers (operations that only report) must state that they leave the state unchanged. This is easy to forget. A peek that quietly reorders items would pass a casual read of its docstring.
Axioms
Axioms describe behavior by relating operations to each other. They never mention storage, so they stay valid for every correct implementation. Each axiom is an equation or a rule that must always hold.
For a stack, two classic axioms are:
- After
push(x),pop()returnsx. - After
push(x)followed bypop(), the stack is in the same observable state as before the push.
Together with the empty-stack error rule, these axioms pin down last-in, first-out behavior without saying how items are kept.
Axioms work best when they cover each observer applied after each constructor or mutator. A useful habit is to build a grid: one row per observer, one column per way of producing a state. Any empty cell is a gap in the specification.
The next chapters build the stack in full. Here we use a smaller ADT, a set of integers, so the axioms can be shown end to end.
A specification for an integer set
Operations:
IntSet()creates an empty set.add(x)is a mutator.remove(x)is a mutator.contains(x)andsize()are observers.
Specification:
- Precondition of
remove(x):contains(x)is true. OtherwiseremoveraisesKeyError. size()is 0 on a new set, andcontains(x)is false for everyx.- After
add(x),contains(x)is true. - After
add(x),contains(y)is unchanged for everyydifferent fromx. - Adding an element that is already present leaves
size()unchanged. Adding a new element increases it by 1. - After
remove(x),contains(x)is false, andsize()is one smaller. - Observers never change the state.
Notice the second-to-last point about add. It rules out an implementation that, say, clears the set whenever it sees a new value. Axioms about what does not change are as important as axioms about what does.
Turning axioms into executable checks
A specification written only in prose can drift. Because axioms are precise, you can encode them as assertions. The check below uses only the public operations, so it works against any implementation.
class ListIntSet:
def __init__(self):
self._items = []
def add(self, x):
if x not in self._items:
self._items.append(x)
def remove(self, x):
if x not in self._items:
raise KeyError(x)
self._items.remove(x)
def contains(self, x):
return x in self._items
def size(self):
return len(self._items)
def check_set_axioms(make_set, x, y):
assert x != y, "the check needs two different values"
s = make_set()
# new set
assert s.size() == 0
assert not s.contains(x)
# add: result, other elements unchanged, size
s.add(x)
assert s.contains(x)
assert not s.contains(y)
assert s.size() == 1
# adding a present element changes nothing
s.add(x)
assert s.size() == 1
# adding a new element grows the set by one
s.add(y)
assert s.contains(x) and s.contains(y)
assert s.size() == 2
# remove: result
s.remove(x)
assert not s.contains(x)
assert s.contains(y)
assert s.size() == 1
# remove: precondition violated gives the specified error
try:
s.remove(x)
except KeyError:
pass
else:
raise AssertionError("remove of a missing element must raise KeyError")
check_set_axioms(ListIntSet, 3, 8)
print("all axioms hold")Running it prints all axioms hold. Each assertion maps to one line of the specification. If you later write a second implementation, for instance one backed by a Python set, you pass its class to check_set_axioms and learn at once whether it keeps the same promises.
The contract view
Preconditions and results form a contract between two parties. The caller promises to meet the precondition. In return, the implementer promises the result.
This split of duties is what lets the two sides work independently. The caller needs to know only the precondition and the result. The implementer needs to know only what must be delivered, and is free to choose any representation that delivers it.
Common errors in specifications
- Describing storage instead of behavior. "Items are kept in a list" locks in a representation. Say "
popreturns the most recently pushed item that has not been popped." - Leaving the error case silent. If the spec does not say what
popdoes on an empty stack, implementations will differ, and clients will depend on whichever one they happened to use. - Forgetting that observers are read-only. State it explicitly, and test it by calling an observer twice and comparing results.
- Missing "nothing else changes" axioms. Without them, a buggy
addthat disturbs other elements still satisfies the positive axioms. - Over-specifying. If the order of elements in a set does not matter to clients, do not promise an order. Every promise you make limits future implementations.
Recap
A signature names an operation. A precondition says what the caller must provide, a result says what the implementer delivers, and axioms say how operations combine. All of them are phrased in terms of abstract values, so they hold for every correct representation. Encode them as checks that use only public operations, and the same checks can be reused for each implementation you write.
Exercise
For the IntSet specification above, suppose an implementer writes add(x) so that it clears the set whenever x is not already present, then stores x. Which axiom does this violate, and why would the test "after add(x), contains(x) is true" still pass?
Show answer
It violates the axiom that adding x leaves contains(y) unchanged for every y different from x, and the size rule (a new element must grow size by 1). The test "after add(x), contains(x) is true" passes because the buggy add does store x. Only axioms that check other elements, or the size, expose the clearing. This shows why a specification needs "nothing else changes" rules.
Exercise
Write the specification lines for an observer is_empty() on a stack, in terms of other operations. Give one axiom for a new stack and one for a stack after a push.
Show answer
For a new stack, isempty() returns True. After push(x) on any stack, isempty() returns False. is_empty() also leaves the state unchanged. None of these lines mention how items are stored.