Sub topic 8
Writing Clients That Depend Only on the Interface
This chapter assumes you have the Stack interface, ListStack, and LinkedStack from the earlier chapters. Save them in a file named stack_adt.py. You should also be comfortable with Python classes, exceptions, and passing functions as arguments.
A client is any code that uses an ADT but is not part of its implementation. A client depends only on the interface when it uses the declared operations and the behavior the specification promises, and nothing else. If a client does that, you can swap ListStack for LinkedStack without editing the client. If it does not, a change of representation can break it.
What the client is allowed to know
For the stack, the specification gives the client four operations: push, pop, peek, and is_empty. It also gives the behavior: last in, first out, and IndexError on pop or peek of an empty stack.
Everything else is off limits. The client may not assume the stack contains a list, that _items or _head exist, or that a particular class was used. It may not assume operations are fast or slow unless the specification says so.
| The client may rely on | The client may not rely on |
|---|---|
| `push`, `pop`, `peek`, `is_empty` | Attributes such as `_items` or `_head` |
| Order of results (last in, first out) | The concrete class of the object |
| `IndexError` on empty `pop` and `peek` | `len(stack)`, `bool(stack)`, or iteration |
| Behavior stated in the docstrings | Speed, memory use, or `repr` output |
A client written against the interface
Bracket matching is a classic stack task. Each opening bracket is pushed. Each closing bracket must match the most recent unmatched opening bracket, which is the top of the stack.
from stack_adt import Stack, ListStack, LinkedStack
PAIRS = {")": "(", "]": "[", "}": "{"}
OPENERS = set(PAIRS.values())
def is_balanced(text, make_stack=ListStack):
stack = make_stack()
for ch in text:
if ch in OPENERS:
stack.push(ch)
elif ch in PAIRS:
if stack.is_empty() or stack.pop() != PAIRS[ch]:
return False
return stack.is_empty()
for make in (ListStack, LinkedStack):
assert is_balanced("{[()]}", make)
assert is_balanced("", make)
assert not is_balanced("(]", make)
assert not is_balanced("((", make)
assert not is_balanced(")", make)
print("is_balanced works with both stacks")The function never names _items, _head, or a concrete class in its body. The only mention of ListStack is the default argument. It checks is_empty() before pop(), so it never triggers the IndexError case by accident. That check follows the precondition in the specification.
Passing the implementation in
is_balanced takes make_stack, a function that returns a new stack. This keeps the choice of implementation in one place, at the edge of the program. There are two reasons for creating the stack inside the function instead of accepting one that already exists.
- A stack passed in might already contain items. The function's result would then depend on state the caller controls.
- The function would also change a stack the caller still owns. Creating its own stack keeps the work local.
Passing the factory is a light form of dependency injection. The client receives its collaborator instead of choosing it. You do not need a framework for this. A function argument is enough.
Three ways a client breaks the contract
Reaching into the representation
from stack_adt import ListStack, LinkedStack
def snapshot_bad(stack):
return list(stack._items) # assumes a list representation
print(snapshot_bad(ListStack())) # []
try:
snapshot_bad(LinkedStack())
except AttributeError as err:
print("broke:", err)This works for ListStack and fails for LinkedStack, because the second class has no _items. The leading underscore is a naming convention. Python does not stop the client, so discipline has to come from you.
Checking the concrete class
def describe_bad(stack):
if isinstance(stack, ListStack):
return "list-backed"
return "unknown"Code like this branches on the implementation. Every new implementation then needs a new branch in every such client. It also rejects valid substitutes, such as the wrapper class shown below.
Relying on behavior the specification never promised
Suppose a client calls len(stack) or writes if stack:. The Stack interface defines neither. It might work today on a class that happens to define __len__, and fail on one that does not. If clients need a size, the right fix is to add a size() operation to the specification and make every implementation provide it.
Until then, a client can compute a count using only the specified operations:
def count(stack):
saved = []
while not stack.is_empty():
saved.append(stack.pop())
for item in reversed(saved):
stack.push(item)
return len(saved)This takes time proportional to the number of items. It leaves the stack as it found it, but it is not safe if another part of the program uses the same stack at the same moment. It shows what the interface alone can do, and it shows why a missing operation is a design question and not something to work around with private attributes.
A substitute the client never anticipated
A strong test of independence is an implementation the client author never saw. This wrapper counts operations and delegates the real work to another stack.
from stack_adt import Stack, LinkedStack
class CountingStack(Stack):
def __init__(self, inner):
self._inner = inner
self.operations = 0
def push(self, item):
self.operations += 1
self._inner.push(item)
def pop(self):
self.operations += 1
return self._inner.pop()
def peek(self):
self.operations += 1
return self._inner.peek()
def is_empty(self):
self.operations += 1
return self._inner.is_empty()Now run the same is_balanced against it. This block assumes is_balanced and CountingStack are already defined in the same file.
made = []
def make_counting():
stack = CountingStack(LinkedStack())
made.append(stack)
return stack
print(is_balanced("(())", make_counting)) # True
print(made[0].operations) # 7The 7 operations are two pushes, two is_empty checks, two pops, and the final is_empty. is_balanced is unchanged, and it now reports how it used the stack. A client with an isinstance(stack, ListStack) check would have rejected this wrapper.
Edge cases that decide whether a client is portable
- Error behavior. The specification says
popon an empty stack raisesIndexError. A client may catchIndexError. It may not catchAttributeErrororTypeErrorand assume those come from emptiness. - Mutation during use. If the specification does not say what happens when a stack is shared, treat sharing as unsafe. Each client should own the stack it works with.
- Stored items. The stack holds references to whatever the client pushes. If the client later mutates a pushed object, the stack's contents change. This is a client concern, and the stack interface does not guard against it.
- Performance. Both stacks give constant-time
pushandpopin the usual analysis, but the specification does not promise it. If a client needs a time bound, the bound should be part of the specification. - Equality and printing. Do not compare two stacks with
==or print them for tests unless the specification defines those operations.
A checklist for reviewing a client
- Does it use only operations named in the interface?
- Does it satisfy every precondition before it calls an operation?
- Does it avoid
isinstancechecks and attribute access on the implementation? - Does it receive its implementation, or create one in a single place?
- Does it pass its tests with every available implementation, including a wrapper?
Exercise
A teammate writes def top_or_none(stack): return stack._items[-1] if stack._items else None. Name two problems with it. Then rewrite it using only the Stack interface.
Show answer
First, it reads _items, so it fails with AttributeError on LinkedStack and on any wrapper such as CountingStack. It depends on the representation instead of the specification. Second, it duplicates the empty check that is_empty and the IndexError rule already express. A correct version is: def top_or_none(stack): return None if stack.is_empty() else stack.peek(). It works with every correct Stack implementation.
Exercise
You need to know how many items a stack holds, and many clients need it. The Stack interface has no size operation. Should each client use len(stack._items)? What should you do instead?
Show answer
No. That ties every client to ListStack's representation. Add size() to the specification, document its behavior (the number of items, 0 for an empty stack), implement it in every Stack class, and add a check for it to the shared behavior test. Clients then call stack.size(). Until that change is made, a client can use the pop-and-restore count function, which is slower but depends only on the interface.