Sub topic 9
Data structure or ADT? Keeping the terms apart
This chapter assumes you have read the earlier chapters on interfaces, behavioral specifications, and the two stack implementations. It also assumes you are comfortable with Python classes, lists, dictionaries, and Big-O notation. The goal is to use the terms abstract data type and data structure precisely, so that design discussions and code reviews stay clear.
Two terms, two questions
People use "data structure" and "ADT" interchangeably in conversation. They answer different questions.
- An abstract data type (ADT) answers: what can I do with this thing, and what will happen? It is a set of operations plus the behavior they promise.
- A data structure answers: how is the data laid out in memory, and how do the steps work? It is a concrete arrangement of storage, such as an array, a linked chain of nodes, or a hash table.
An ADT is a specification, and a data structure is a technique for storing data. An implementation of an ADT usually uses one or more data structures, together with code that makes the operations keep their promises.
| Aspect | ADT | Data structure |
|---|---|---|
| Describes | Operations and their behavior | Storage layout and algorithms |
| Visible to clients | Yes, this is the contract | Should not be |
| Example | Stack, Queue, Set, Map | Array, linked list, hash table, binary tree |
| Cost analysis | Stated only if the spec promises it | Intrinsic to the layout |
| Can change without breaking clients | Not without breaking them | Yes, if the ADT's contract still holds |
The relationship is many-to-many
The mapping between the two is not one-to-one in either direction.
The earlier chapters showed one ADT with several data structures: Stack implemented by ListStack and LinkedStack. The next sections show the reverse, one data structure serving several ADTs. Then they show a case where choosing the data structure quietly changes the contract.
One data structure, different ADTs
A Python list is a data structure: a resizable array of references. It does not say whether the last item or the first item comes out first. That decision belongs to the ADT.
class ListStack:
"""Last in, first out."""
def __init__(self):
self._items = []
def add(self, x):
self._items.append(x)
def remove(self):
if not self._items:
raise IndexError("remove from empty stack")
return self._items.pop()
class ListQueue:
"""First in, first out."""
def __init__(self):
self._items = []
def add(self, x):
self._items.append(x)
def remove(self):
if not self._items:
raise IndexError("remove from empty queue")
return self._items.pop(0)
stack = ListStack()
queue = ListQueue()
for n in (1, 2, 3):
stack.add(n)
queue.add(n)
print(stack.remove()) # 3
print(queue.remove()) # 1Both classes store items in the same kind of list and expose the same operation names. They still behave differently, because the specifications differ. The data structure gave neither of them its behavior. The behavior came from the rule each class follows when it removes an item.
Notice also that ListQueue.remove calls pop(0), which shifts every remaining item left. That cost comes from the data structure. A different layout, such as a linked chain with a tail pointer, would not have it. The queue ADT does not change, but the cost does.
One ADT, different data structures, different fine print
You might expect any correct data structure to be a drop-in replacement. Usually it is, but a data structure can impose requirements that the ADT never mentioned. Consider a set of values with add and contains.
class ListSet:
"""A set backed by a list. Needs only == on elements."""
def __init__(self):
self._items = []
def add(self, x):
if x not in self._items:
self._items.append(x)
def contains(self, x):
return x in self._items
class HashSet:
"""A set backed by a hash table. Elements must be hashable."""
def __init__(self):
self._items = set()
def add(self, x):
self._items.add(x)
def contains(self, x):
return x in self._items
for make_set in (ListSet, HashSet):
s = make_set()
s.add(1)
print(make_set.__name__, s.contains(1), s.contains(2))
try:
s.add([1, 2])
print(make_set.__name__, "accepted a list element")
except TypeError as e:
print(make_set.__name__, "rejected a list element:", e)Running it prints:
ListSet True False
ListSet accepted a list element
HashSet True False
HashSet rejected a list element: unhashable type: 'list'Both classes pass the same basic checks, yet a client that adds lists works with one and crashes with the other. The data structure leaked into the contract.
There are two sound ways to handle this.
- Strengthen the spec. State a precondition: "elements must be hashable." Every implementation must then accept every hashable element, and clients may not rely on anything more. The
ListSetis still correct, because it accepts more than the spec requires. - Weaken the data structure's demands. Choose a structure, or add conversion code, so the original wider contract holds.
The first choice is common. The important habit is to write the requirement into the specification, so that it is not discovered by accident when someone swaps implementations.
Library names blur the line
Real libraries do not always keep the terms separate. Knowing the common patterns helps you read them.
- Java:
Listis an interface, which is an ADT.ArrayListandLinkedListare classes that implement it, each built on a data structure.ArrayListis named after its layout. - Python:
listanddictare concrete types. They also serve as the standard way to write lists and maps, and the documentation promises certain behavior and costs. In practice they act as both a data structure and the ADT clients use. - C++:
std::vectorandstd::listare named after layouts, whilestd::stackis an adapter. It wraps another container and exposes only the stack operations. - Informal speech: "a stack" can mean the ADT (the contract) or a particular array-based class. Ask which one is meant if it affects a decision.
The std::stack adapter shows the idea cleanly. It takes a data structure that offers more operations than you want and exposes only the subset that defines the ADT. That narrowing is information hiding at work.
Reading a sentence for its level
A quick check helps when you read or write design notes. Ask whether a sentence is about the contract or about the layout.
| Sentence | Level |
|---|---|
| "`pop` returns the most recently pushed item." | ADT |
| "`pop` removes the head node." | Data structure |
| "A queue must raise an error when empty." | ADT |
| "Appending to the end of an array is amortized constant time." | Data structure |
| "Use a hash table so `contains` is fast." | Data structure, chosen to meet a cost goal |
| "Elements must be hashable." | Contract that a data structure forced into the spec |
Mixing levels in one sentence is a sign that the design is leaking. For example, "the stack is a linked list" in a client-facing document tells readers a layout they should not rely on.
Common errors
- Equating the ADT with its first implementation. If you write the spec after the code, the spec tends to describe the code, including accidents such as the order a list happens to iterate in. Write the behavior first.
- Exposing the layout in the interface. A method like
get_head_node()ties every client to a linked chain. Expose operations, not storage. - Assuming the same cost. The ADT promises behavior. Costs belong to the implementation unless the spec states them, as in "
pushis O(1) amortized." - Treating inherited convenience as part of the ADT. If
ListStacksubclasseslist, theninsert,sort, and slicing become reachable. Clients may start using them, and the contract has silently grown to include them. - Using the data structure's name as the ADT's name. A class called
ArrayStacktells clients about its layout. That is fine for a concrete implementation class, but the interface it implements should be named for the abstraction.
Exercises
Exercise
A teammate says, "A hash table is an abstract data type that maps keys to values." Rewrite this sentence so it keeps the two terms apart.
Show answer
"A map (or dictionary) is an abstract data type that maps keys to values. A hash table is one data structure that can implement it." The map is the contract of operations and behavior. The hash table is a layout and algorithm that meets the contract, and other structures such as balanced trees could also implement it.
Exercise
You replace a ListSet with a HashSet and a client that adds tuples keeps working, but a client that adds lists now raises TypeError. Which two fixes keep the design sound, and which party is at fault in each?
Show answer
Either add the precondition "elements must be hashable" to the Set specification, in which case the client that adds lists was relying on behavior the spec never promised and must change. Or keep the original wider contract and make HashSet meet it, for example by rejecting nothing and converting or wrapping unhashable elements, in which case the implementation was at fault for narrowing the contract. In both cases the fix belongs to the spec or the implementation, not to a special case in the client.