Sub topic 8
Writing clients that depend only on the interface
This chapter assumes you know the Stack interface and its two implementations, ListStack and LinkedStack, from earlier chapters. It also assumes you can read Python classes and exceptions.
What a client is
A client is code that uses an ADT without being part of it. A function that checks whether brackets match is a client of Stack. It needs push, pop and is_empty, and nothing about how items are stored.
A client depends only on the interface when every line it writes about the stack is justified by the specification. If you swap the implementation for any other correct one, the client keeps working.
A client written against the specification
The function below checks whether brackets in a string are balanced. It receives a make_stack function that creates an empty stack. It never names a concrete class.
class ListStack:
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
class _Node:
def __init__(self, value, next_node):
self.value = value
self.next = next_node
class LinkedStack:
def __init__(self):
self._head = None
def push(self, item):
self._head = _Node(item, self._head)
def pop(self):
if self._head is None:
raise IndexError("pop from empty stack")
value = self._head.value
self._head = self._head.next
return value
def is_empty(self):
return self._head is None
def is_balanced(text, make_stack):
pairs = {")": "(", "]": "[", "}": "{"}
stack = make_stack()
for ch in text:
if ch in "([{":
stack.push(ch)
elif ch in pairs:
if stack.is_empty() or stack.pop() != pairs[ch]:
return False
return stack.is_empty()
for make_stack in (ListStack, LinkedStack):
print(is_balanced("{[()]}", make_stack), is_balanced("(]", make_stack))
# True False
# True FalseThe client checks is_empty() before calling pop(). The specification says pop() raises IndexError on an empty stack. The client therefore meets the precondition itself and does not rely on catching an error.
The implementation is chosen in one place, the argument to is_balanced. Passing the choice in keeps the client free of any class name.
What breaks the dependency
Clients lose their independence in a few common ways.
- Reaching into the representation. Code such as
stack._items[-1]works forListStackand fails forLinkedStack. Usepeek()instead. - Checking the concrete type.
isinstance(stack, ListStack)ties the client to one class. - Relying on unspecified behavior. Suppose a client calls
pop()on an empty stack and assumes it returnsNone. A particular implementation might do that, but the specification promisesIndexError. - Constructing a concrete class deep inside. A hard-coded
ListStack()in the middle of a function forces a code change for every new implementation.
How the dependencies flow
Both arrows end at the interface. This is why you can replace one implementation with another without editing the client.
A practical test
Ask this question of every line in a client: "Could I justify this line by reading only the specification?" If the answer is no, the line depends on an implementation. Either move that knowledge behind the interface, or change the specification and update every implementation.
A client written this way is also easier to test. You can pass in a fake stack that records calls, and you do not need to build the real one.
Exercise
A teammate writes def top_or_none(stack): return stack._items[-1] if stack._items else None. Name two ways this breaks the dependency on the interface, and rewrite it using only the Stack operations.
Show answer
It reads the private attribute _items, which exists only in ListStack, so it fails for LinkedStack. It also assumes a representation (a list) that the specification does not promise. A correct version is def top_or_none(stack): return None if stack.is_empty() else stack.peek().