Sub topic 12
Representation invariants
This chapter assumes you know what an abstract data type (ADT) is, can read Python classes, and understand that an ADT's operations are separate from the data structure behind them.
What a representation invariant is
An implementation stores an ADT's values in a concrete representation, such as a list. Not every possible list is a valid representation. If IntSet stores its elements in a list, a list with duplicates would make no sense as a set.
A representation invariant is a condition on the representation that must be true for every object that exists outside an operation. It separates valid internal states from invalid ones. Every operation can assume it holds on entry, and every operation must make sure it holds on exit.
Writing the invariant down
Write the invariant in the class documentation, next to the description of what the representation means. Then check it in code.
class IntSet:
"""A set of integers.
Abstraction function: the list [a, b, c] represents the set {a, b, c}.
Representation invariant: _items contains no duplicates.
"""
def __init__(self):
self._items = []
self._check_rep()
def _check_rep(self):
assert len(self._items) == len(set(self._items))
def add(self, x):
if x not in self._items:
self._items.append(x)
self._check_rep()
def contains(self, x):
return x in self._items
def size(self):
return len(self._items)_check_rep compares the list length with the length of a set built from the list. If they differ, the list has a duplicate and the assertion fails. The constructor and add call it before returning. contains and size don't change the state, so they don't need to.
Why the invariant matters
The invariant lets each operation stay simple. size returns len(self._items). That is correct only because duplicates cannot exist. If the invariant were not guaranteed, size would have to count distinct items every time.
Inside an operation the invariant may be briefly false. A method that updates two fields can leave them inconsistent between the two assignments. That is acceptable as long as the invariant holds again before the method returns.
What breaks an invariant
Two things commonly break it.
- A bug in a mutator. Suppose someone "optimizes"
addto skip thex not in self._itemstest. The first repeatedadd(3)now fails the assertion insideadd, which points straight at the faulty method. - Outside access to the representation. If a client can reach
_itemsdirectly, it can append a duplicate and no operation will notice until later. The next chapters cover this problem, called representation exposure.
Practical advice
- Call
_check_repat the end of every constructor and every mutator. For methods that return internal data, also call it on entry. - Use
assertfor the check. It documents the invariant in executable form and can be switched off withpython -O. Checks that cost a lot, such as the one above, which is O(n), are best kept for tests and debugging. - State the invariant before you write the operations. It tells you what each one must preserve.
- Keep invariants as strong as the operations need. Add "the list is sorted" only if your operations rely on it.
Exercise
A programmer changes IntSet.add to always call self.items.append(x), without testing membership first. Which call is the first to make check_rep fail, and why does size() become wrong without the check?
Show answer
The first call that adds a value already in the set, such as add(3) twice, fails the assertion at the end of the second add, because the list then has a duplicate. Without the check, size() returns len(self._items), which would count 3 twice and report a larger size than the set actually has.