Sub topic 5
Interface versus implementation
This chapter assumes you can write Python classes, raise and catch exceptions, and work with lists and references. It also assumes you know that an abstract data type (ADT) is defined by its operations and their promised behavior.
Two sides of one type
Every ADT has two sides.
- The interface is what a client can see and rely on. It holds the operation names, their signatures, and the behavior they promise, including error cases.
- The implementation is the representation (the data actually stored) plus the code that makes each operation keep its promise.
The client talks only to the interface. The implementation can change without the client noticing, as long as it keeps the promise.
What belongs on each side
| Belongs to the interface | Belongs to the implementation |
|---|---|
| Operation names and parameters | Fields such as `_items` or `_head` |
| Results and preconditions | Helper methods and node classes |
| Errors the caller can expect | Choice of list, linked chain, or other storage |
| Cost promises, if any are stated | Actual cost of the chosen representation |
The boundary in code
The abstract class below is the interface. Its docstring is the specification.
from abc import ABC, abstractmethod
class Stack(ABC):
"""A last-in, first-out collection.
push(x) then pop() returns x.
pop() raises IndexError on an empty stack.
"""
@abstractmethod
def push(self, item):
"""Add item to the top of the stack."""
@abstractmethod
def pop(self):
"""Remove and return the top item."""
@abstractmethod
def is_empty(self):
"""Return True if the stack has no items."""
class ListStack(Stack):
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
def is_empty(self):
return not self._items
def drain(stack):
out = []
while not stack.is_empty():
out.append(stack.pop())
return out
s = ListStack()
s.push("a")
s.push("b")
print(drain(s)) # ['b', 'a']drain uses only is_empty and pop. It would work unchanged with any other correct Stack.
Common errors
- Reaching past the interface. A client that reads
s._itemsnow depends on the list. Switching to a linked chain breaks it. - Leaking the representation through an operation. An operation that returns the internal list lets callers change state without using the interface.
- Leaving the specification silent. If the spec does not say what
popdoes on an empty stack, each implementation will choose differently, and clients will start relying on whichever one they happened to see. - Adding unspecified behavior. If one implementation returns
Noneon an emptypopwhile the spec says to raiseIndexError, it breaks the substitutability of implementations.
Exercise
A teammate changes ListStack to store items in a tuple, creating a new tuple on each push. A client function that only calls push, pop, and is_empty still passes its tests. Another client reads stack._items[-1] and now fails. Which client was written against the interface, and why did the other one break?
Show answer
The first client was written against the interface. It uses only the specified operations, so any representation that keeps their behavior is safe. The second client depended on the private field _items, which is part of the implementation and not the promise. When the representation changed, that dependency broke. A fix is to add a peek operation to the specification and have the client call it.