Sub topic 3
Describing an ADT by its operations
This chapter assumes you can read Python classes and know what a return value and an exception are. It also assumes you have met the idea of an abstract data type (ADT) as a set of operations with promised behavior. Here you learn to describe an ADT by listing its operations and sorting them by what they do. The next chapter covers how to state their behavior precisely.
Operations are the whole interface
A client of an ADT can do only what the operations allow. It cannot look inside, so the operations are everything it knows about the type. Describing an ADT therefore starts with a list of operations, and each entry on the list has two parts:
- A name.
- A signature, which gives the types of the inputs and the type of the result.
For a stack of items of type T, the signatures look like this:
| Operation | Signature | What it does, in a phrase |
|---|---|---|
| `Stack()` | `() -> Stack` | Makes an empty stack |
| `push` | `(Stack, T) -> void` | Adds an item on top |
| `pop` | `(Stack) -> T` | Removes and returns the top item |
| `peek` | `(Stack) -> T` | Returns the top item |
| `is_empty` | `(Stack) -> bool` | Tells whether any items remain |
A signature says nothing about storage, and that is deliberate. A signature also does not say what an operation does. push and pop could have these same signatures and still do unrelated things, so the signature is only the first half of a description.
Three categories of operation
Every operation of an ADT falls into one of three categories, based on how it relates to the type being defined. Call that type A.
- A constructor produces a value of type
Awithout needing an existing one.Stack()is a constructor. Its signature hasAin the result only. - A mutator changes an existing value of type
A.pushis a mutator. After it runs, the stack holds different contents than before. - An observer takes a value of type
Aand returns information about it, usually of some other type.is_emptyandpeekare observers. They leave the value unchanged.
Some authors split out a fourth category, producers. A producer takes existing values of type A and returns a new value of type A, leaving the inputs alone. String concatenation is a producer, and so is set.union in Python. Treat producers as constructors that also take an A as input. Immutable types rely on them, as the next sections show.
The categories matter because they show what a type can do. A type with no constructor cannot be used, since no value ever exists. A type with no observer is useless in a quieter way, as the next section shows.
Reading the categories from signatures
You can often classify an operation from its signature alone. Look at where the ADT type A appears.
| `A` appears in the inputs | `A` appears in the result | Category |
|---|---|---|
| No | Yes | Constructor |
| Yes | Yes | Producer (immutable) or mutator that also returns the type |
| Yes | No, or `void` | Observer if it returns information, mutator if it returns `void` |
A void result is a strong hint. An operation with A as input and nothing useful returned can only be useful if it changes something, so it is a mutator.
Operations that are two things at once
Real operations often combine categories. pop is the standard case. It changes the stack by removing the top, and it also reports the item it removed. It is both a mutator and an observer.
Python's own list.pop works the same way. Some designs avoid the mix by splitting it into two operations. For example, peek observes the top and a separate drop removes it. The combined form is shorter to call. The split form lets you look at the top without removing it and makes each operation easier to specify. Neither design is wrong, but you should know which one you have chosen.
The same ADT in a mutable and an immutable style
Whether operations change a value or return a new one is a design choice, and it changes the categories. Compare two stack designs:
- In the mutable design,
pushis a mutator. It returns nothing and changes the stack. - In the immutable design,
pushis a producer. It returns a new stack and leaves the old one alone.
The following code shows the immutable form. The stack stores its items in a tuple, which Python cannot change after creation.
class FrozenStack:
def __init__(self, items=()):
self._items = tuple(items)
def push(self, item):
return FrozenStack(self._items + (item,))
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return FrozenStack(self._items[:-1])
def top(self):
if not self._items:
raise IndexError("top of empty stack")
return self._items[-1]
def is_empty(self):
return not self._items
s0 = FrozenStack()
s1 = s0.push(1)
s2 = s1.push(2)
print(s2.top(), s1.top(), s0.is_empty()) # 2 1 True
print(s2.pop().top()) # 1Here FrozenStack() is the constructor. push and pop are producers. top and is_empty are observers. There are no mutators. Because pop now returns the shortened stack and not the item, reading the top item needs its own observer, top. This is the split design from the previous section, and the immutable style forces it.
Immutable ADTs have a benefit. A value never changes under you, so sharing it between parts of a program is safe. The cost is that every producer builds a new value. Here that means copying the tuple on each push, which takes time proportional to the stack size. A cleverer representation can avoid the copying, but that is an implementation choice and does not change the operations.
Choosing a good set of operations
How do you decide which operations an ADT needs? Three tests help.
- Can you create a value? At least one constructor must exist.
- Can you tell any two different values apart? If two abstract values give identical answers from every observer, a client cannot distinguish them. Either the values really are the same, or an observer is missing.
- Can you reach every value? Combinations of constructors and mutators should be able to build every value you intend the type to hold.
The second test catches a common design mistake. Consider this counter:
class BrokenCounter:
def __init__(self):
self._count = 0
def increment(self):
self._count += 1A client can create a counter and increment it, but it can never learn the count. Counters holding 0 and 1000 behave the same from outside. The type has a constructor and a mutator and no observer, so it carries no usable information. Adding one observer fixes it:
class Counter:
def __init__(self):
self._count = 0
def increment(self):
self._count += 1
def value(self):
return self._count
c = Counter()
c.increment()
c.increment()
print(c.value()) # 2Now the observers can distinguish counters by their histories: a counter incremented twice answers 2 and a fresh one answers 0.
You also want the set to be small. Every operation is something every implementation must support and every client may come to depend on. A common guideline is to provide a few operations that cannot be built from the others, and to leave out conveniences a client could write itself. For example, a reverse function built on push, pop and is_empty does not need to be an operation of the stack, because it uses only the public operations.
Classifying operations in practice
When you meet an unfamiliar type, you can describe it by answering these questions for each operation:
- Does it need an existing value of the type as input? If not, it is a constructor.
- Does it change that value? If so, it is a mutator.
- Does it return information about the value? If so, it is an observer.
- Does it return a new value of the same type? If so, it is a producer.
Try it on Python's built-in set:
| Operation | Category |
|---|---|
| `set()` | Constructor |
| `s.add(x)` | Mutator |
| `s.remove(x)` | Mutator, and it can raise `KeyError` |
| `x in s` | Observer |
| `len(s)` | Observer |
| `a.union(b)` | Producer |
Note the sixth row. union leaves a and b unchanged and returns a new set. The mutator update does the same job in place. Python often gives both forms for one idea.
Common errors
- Listing operations without signatures. A name alone leaves out input and result types, and so hides whether an operation returns a value or changes the object.
- Forgetting the error cases. Operations such as
popandtophave inputs for which they cannot give a normal answer. The description must say so. The next chapter treats this under preconditions. - Making every operation a mutator. A type with only constructors and mutators gives clients no way to see inside. Check that observers exist.
- Mixing mutation and production without saying so. A method that both changes
selfand returns a new object is confusing. Choose one style per type. - Adding operations that expose the representation. An operation such as
get_list()on a stack gives clients the internal storage. This ties them to one implementation and is the subject of a later chapter on representation exposure.
Exercise
A Queue ADT for items of type T has these operations: Queue(), enqueue(Queue, T), dequeue(Queue) which removes the front item and returns it, front(Queue) which returns the front item without removing it, and size(Queue) which returns an int. Classify each operation as constructor, mutator, observer, or both mutator and observer.
Show answer
Queue() is a constructor, since no queue is needed as input. enqueue is a mutator, since it takes a queue and changes it. dequeue is both a mutator and an observer, since it changes the queue and returns the removed item. front and size are observers, since they return information and leave the queue unchanged.
Exercise
This Switch class has a constructor and a mutator flip() that toggles an internal boolean. Explain what is wrong with it as an ADT, and name the operation you would add.
Show answer
It has no observer, so a client can never learn whether the switch is on or off. Every switch looks the same from outside. Add an observer such as is_on(Switch) -> bool.