Make the contract explicit

Lesson 13 of 19 · Python Object Design

A contract describes what callers must provide and what they can expect in return. It includes ordinary results, side effects and failure behavior. For a simple first-in, first-out collection of labels, agree that empty means None; accepted labels must therefore never be None.

class LabelLine:
    def __init__(self):
        self._labels = []

    def put(self, label):
        if not isinstance(label, str) or not label:
            raise ValueError("label must be a nonempty string")
        self._labels.append(label)

    def take(self):
        if not self._labels:
            return None
        return self._labels.pop(0)

line = LabelLine()
line.put("north")
line.put("south")
print(line.take())
print(line.take())
print(line.take())

Output:

north
south
None

put returns None implicitly and changes the line. take removes and returns the oldest label, or returns None without removing anything when empty. Invalid put calls raise before insertion. A caller can check result is None without confusing an empty line with an accepted label.

put(label) -> [ oldest ... newest ] -> take() -> label or None

This implementation uses a list; a different internal collection could serve the same contract. This small example makes no promise about persistence, multiple threads or performance. Those properties belong in the contract when callers need them. Renaming take, reversing the order, or replacing None with an exception changes what callers can rely on even if the replacement looks simpler.

Chapter contents