Sub topic 6
A worked example: the stack ADT
This chapter assumes you know Python classes, exceptions, and the idea of an interface from the earlier chapters. It applies those ideas to one small ADT, the stack.
What a stack promises
A stack is a collection where the last item added is the first one removed. This is called last-in, first-out (LIFO). Think of a pile of plates. You add to the top and take from the top.
The stack is a good first ADT because its promise is short. Four operations cover it, and each fits one of the categories from earlier in this tutorial.
| Operation | Category | Behavior |
|---|---|---|
| `push(item)` | Mutator | Adds `item` to the top |
| `pop()` | Mutator and observer | Removes and returns the top item |
| `peek()` | Observer | Returns the top item without removing it |
| `is_empty()` | Observer | Returns `True` if there are no items |
Creating an empty stack is the constructor. In Python that is the class's __init__, so it does not appear in the interface below.
The behavioral specification
A list of names is not a specification. The behavior has to be stated too. For the stack, three rules do most of the work:
- After
push(x),peek()returnsxandis_empty()isFalse. push(x)followed bypop()returnsxand leaves the stack as it was before the push.pop()andpeek()on an empty stack raiseIndexError.
Rules 1 and 2 are axioms, which are equations that hold for any correct stack. Rule 3 is the error case. We chose to make it a defined failure instead of a precondition the caller must never break. The caller can rely on it either way.
The interface in code
In Python, an abstract base class can carry both the operation names and the promised behavior. The docstrings are the specification.
from abc import ABC, abstractmethod
class Stack(ABC):
"""A last-in, first-out collection.
push(x) then pop() returns x.
pop() and peek() raise 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 peek(self):
"""Return the top item without removing it."""
@abstractmethod
def is_empty(self):
"""Return True if the stack has no items."""Nothing here says how items are stored. There is no list, no node, and no size counter. A subclass that fails to define all four methods cannot be instantiated, so Python enforces the shape of the interface. It does not enforce the behavior. Only a test can check that, which a later chapter covers.
How a stack changes state
The diagram shows what a client can observe. It does not show storage.
Why this example matters
Look at what you now have. You have a name, four operations, and a set of rules. You have no storage decision. Any class that follows the rules is a stack, whether it keeps items in an array, a chain of nodes, or something else.
That is the central point of this tutorial. The specification is the ADT. An implementation is one way to satisfy it. The next chapter builds two implementations of this exact interface.
Exercise
A teammate adds a method size() to one stack implementation but not to the Stack interface, then uses size() in client code. What goes wrong, and what are two ways to fix it?
Show answer
The client now depends on a method that is not part of the specification, so it breaks with any other correct implementation. One fix is to remove the call and use only the interface operations. The other is to add size() to Stack with a documented behavior and require every implementation to provide it.