Sub topic 5
Interface versus implementation
This chapter assumes you can read Python classes, know what an exception is, and know that a list stores items in order. It also assumes you have met the idea of an abstract data type (ADT) as a set of operations with promised behavior. Here you will separate the two halves of every ADT: the interface that clients see and the implementation that does the work.
Two views of one object
Every class can be read from two sides.
- The interface is everything a client may rely on. It includes the operation names, their parameters, their results, the errors they raise, and the behavior the documentation promises.
- The implementation is everything else. It includes the fields, the helper methods, the algorithm each operation uses, and the order in which it does things.
A client is code that uses the ADT. The implementer is the person who writes the class. These roles can belong to the same person on the same day, but the discipline still applies. When you write the client, you act as if you cannot see the implementation. When you write the implementation, you act as if you cannot see the clients.
The rule that connects the two sides is simple. Clients may depend on the interface. They may not depend on the implementation. If a client follows the rule, you can replace the implementation with another correct one and the client keeps working.
What belongs in the interface
The interface is more than a list of method names. A method name tells a client almost nothing about what happens when it is called. The interface has four parts.
- Signatures. The names, parameters, and return values of the operations.
- Behavior. What each operation does, stated as a result or as a change in what the object represents.
- Preconditions and errors. The inputs the operation accepts, and what it does with the others. For example, "raises
IndexErroron an empty stack" belongs here. - Cost promises, when they matter. If a client needs
pushto be fast, the documentation can say so. If you promise nothing about cost, clients should not assume anything.
Python does not enforce most of this. A client can call any method it can name, and the language will not stop it from reading a field. The interface exists because the author wrote it down and the clients agreed to respect it.
What belongs in the implementation
The implementation is every decision you may change later without telling anyone. Typical examples:
- Whether items live in a list, a linked chain, or a dictionary.
- Whether a value is stored or recomputed each time it is asked for.
- The names of fields and private helper methods.
- Whether the object caches results.
A useful test is to ask: "If I changed this, would a correct client notice?" If the answer is no, it is implementation. If the answer is yes, it is interface, and you should have written it down.
A small example
The following ADT is deliberately tiny so the split is easy to see. A counter starts at zero, can be incremented, and can report its value.
from abc import ABC, abstractmethod
class Counter(ABC):
"""A counter that starts at zero and only counts up.
increment() adds one to the count.
value() returns the number of increments so far.
"""
@abstractmethod
def increment(self):
"""Add one to the count."""
@abstractmethod
def value(self):
"""Return the number of increments so far."""
class IntCounter(Counter):
def __init__(self):
self._count = 0
def increment(self):
self._count += 1
def value(self):
return self._count
class TallyCounter(Counter):
def __init__(self):
self._marks = []
def increment(self):
self._marks.append("|")
def value(self):
return len(self._marks)
def count_words(text, counter):
for _ in text.split():
counter.increment()
return counter.value()
for make_counter in (IntCounter, TallyCounter):
print(count_words("to be or not to be", make_counter()))
# 6
# 6Counter is the interface. It says what the operations do and says nothing about storage. IntCounter keeps one integer. TallyCounter keeps one mark per increment. The two stores are very different, yet count_words cannot tell them apart. It calls only increment and value, which are the two operations the interface promises.
The arrows in the diagram carry the rule. The client points at the interface only. No arrow runs from the client to IntCounter or TallyCounter, so replacing one with the other changes nothing the client can see.
How clients break the boundary
Python lets a client ignore the interface. The leading underscore on _count is a convention that means "private to this class", and the language does not enforce it. Here is a client that reaches past the interface.
def count_words_fast(text, counter):
for _ in text.split():
counter.increment()
return counter._count # reads the representation directly
print(count_words_fast("to be or not to be", IntCounter())) # 6
try:
print(count_words_fast("to be or not to be", TallyCounter()))
except AttributeError as error:
print("broken:", error)With IntCounter the function works, and that is the danger. It works today and gives the author no reason to doubt it. With TallyCounter it raises AttributeError, because no field named _count exists. The client was never correct. It only appeared correct, because it was tested with one implementation.
Which changes are safe
You can sort any edit to a class by asking whether it touches the interface. The table gives common edits and their effect on a correct client.
| Edit | Interface changed? | Effect on a correct client |
|---|---|---|
| Rename a private field | No | None |
| Replace a list with a dictionary inside | No | None |
| Make `value()` faster | No | None, unless it now returns different results |
| Add a new public method | Yes, extended | None, as existing calls still work |
| Rename a public method | Yes | Clients must change |
| Raise a new exception type from `pop()` | Yes | Clients that catch the old type may break |
| Change what `value()` returns for the same history | Yes | Clients may break silently |
The last two rows are the dangerous ones. They keep the method names, so no tool flags them, but they change the promised behavior. Treat the behavior text as part of the interface when you review a change. Do not look only at the signatures.
Strengthening and weakening promises
Not every change to behavior breaks clients. Two directions are worth knowing.
- An implementation may do more than the interface promises. For example, if the documentation says
value()returns a count, an implementation may also keep a history. Clients that rely only on the promise are unaffected. - An implementation must never do less. If the interface promises that
pop()raisesIndexErroron an empty stack, an implementation that returnsNonein that case breaks clients that catch the exception.
This is the working meaning of "correct implementation". It is not "an implementation that works for my tests". It is "an implementation that keeps every promise the interface makes".
Where Python draws the line
Python has several ways to state an interface, and they differ in how much they enforce.
- An abstract base class (as with
Counterabove) refuses to create an object unless every abstract method is defined. That checks names but not behavior. - A docstring records the behavior, the preconditions, and the errors. Nothing checks it, so it needs tests.
- A leading underscore marks a name as part of the implementation. Tools and reviewers can see the mark, but Python itself does nothing about it.
Because enforcement is weak, you have to supply the discipline yourself. Write the promises down, keep implementation names private, and test every implementation against the same promises. A later chapter returns to language mechanisms and to testing in detail.
A routine for writing both sides
- Write the interface first. List the operations, then write the behavior of each in a sentence or two, including errors.
- Write a client, even a three-line one, using only those operations. If it feels awkward, fix the interface now while changes are cheap.
- Write one implementation. Mark all fields and helpers private.
- Check that no client code names a private field.
- When you change the implementation later, run the same client code against both versions.
Common errors
- Documenting the representation instead of the behavior. A docstring that says "stores items in a list" tells clients about the implementation. Say "the most recently pushed item is returned first".
- Leaving error cases unstated. If the interface says nothing about an empty stack, one implementation may raise and another may return
None. Clients will then depend on whichever they tried first. - Testing only one implementation. A client that passes against one class has shown only that it works with that class.
- Returning internal objects. A method that returns a private list gives clients a way to change state without calling any operation. The representation exposure chapter covers this.
Exercise
A teammate changes IntCounter to store its count as a string such as "6" and converts it back inside value(). The interface is unchanged. Is countwords still correct? Is countwords_fast still correct? Explain what the difference shows.
Show answer
countwords is still correct, because it calls only increment() and value(), and value() still returns the integer count the interface promises. countwordsfast is now wrong: it reads count directly and would return the string "6" instead of the integer 6. The difference shows that a client using only the interface survives any change that keeps the promises, while a client that reads a private field depends on the implementation and breaks when the representation changes.