Sub topic 2
What an abstract data type is
This chapter defines an abstract data type (ADT) and separates the idea from the code that realizes it. It assumes you can write Python classes, know what lists and references are, understand return values and exceptions, and have seen Big-O notation. Later chapters cover how to specify operations precisely, the stack in detail, and the checks that keep an implementation honest. Here the goal is a clear definition and a way of thinking you can apply to any type.
The definition
An abstract data type is a kind of value or object described entirely by the operations it offers and the behavior those operations promise. It says nothing about how the values are stored in memory.
An ADT has two parts:
- The operations. Each one has a name, input types, and a result type. Together they are the only way a client touches the data.
- The promised behavior. This describes what each operation does, when it may be called, and what happens when something goes wrong.
An implementation is one concrete way to meet that promise. It chooses a representation (the fields and structures that hold the data) and writes the code for each operation. A client is any code that uses the ADT through its operations.
The word "abstract" means the type is defined by what you can do with it, not by what it is made of. Python's built-in int works this way. You add, compare, and print integers without knowing how the interpreter lays out their digits in memory. The interpreter could change that layout in a new release, and your arithmetic would still work.
A first example: an event counter
Suppose you need to count events. The ADT, described in prose, looks like this:
Counter()creates a counter whose value is 0.increment()adds one to the counter.value()returns how many increments have happened.
That is the whole ADT. Here is one implementation:
class Counter:
"""Counts events. value() is the number of increment() calls so far."""
def __init__(self):
self._count = 0
def increment(self):
self._count += 1
def value(self):
return self._countHere is a client that depends only on the three operations:
def count_matches(events, wanted, counter):
for event in events:
if event == wanted:
counter.increment()
return counter.value()
print(count_matches(["a", "b", "a", "c", "a"], "a", Counter())) # 3Now consider a different implementation of the same ADT:
class TallyCounter:
"""Same promise as Counter, but records one mark per event."""
def __init__(self):
self._marks = []
def increment(self):
self._marks.append("|")
def value(self):
return len(self._marks)
print(count_matches(["a", "b", "a", "c", "a"], "a", TallyCounter())) # 3count_matches is unchanged and produces the same answer. The two classes have different fields (an integer versus a list) and different memory use, but they offer the same operations with the same behavior. Both implement one ADT. The ADT is the promise, and each class is one way to keep it.
What the definition leaves out
An ADT definition deliberately omits several things. Each omission is what gives you freedom to change the code later.
- Field names and types.
_countand_marksdo not appear in the promise. - Algorithms. The promise does not say whether
value()reads a stored number or counts a list. - Cost. An ADT's operations can promise results without promising speed. In practice you also care about cost, and a later chapter treats that choice directly.
- Which language feature is used. A class, a module of functions, or a record plus helper functions can all deliver the same ADT.
A contrast: the same idea without abstraction
To see why the definition matters, consider code that has no ADT. A program keeps a plain list of [name, score] pairs and every part of it reaches into that list directly:
scores = [["Ada", 90], ["Grace", 85]]
# Code scattered through the program:
total = 0
for entry in scores:
total += entry[1]
print(total / len(scores))Every place that writes entry[1] depends on the position of the score in each pair. If you later switch to a dictionary keyed by name, you must find and edit every one of those places. The code is correct, but the decision about representation has spread everywhere.
An ADT concentrates that decision. You define operations such as add_score(name, score) and average(), and only the class body knows about pairs or dictionaries:
class Gradebook:
"""A mapping from student name to one score.
add_score(name, score) records or replaces the score for name.
average() returns the mean score. Raises ValueError if there are no scores.
"""
def __init__(self):
self._scores = {}
def add_score(self, name, score):
self._scores[name] = score
def average(self):
if not self._scores:
raise ValueError("average of no scores")
return sum(self._scores.values()) / len(self._scores)
book = Gradebook()
book.add_score("Ada", 90)
book.add_score("Grace", 85)
print(book.average()) # 87.5The docstring is part of the ADT. It states that adding a score for an existing name replaces it, and that average() raises ValueError when there is nothing to average. A client can rely on both facts without reading the method bodies. How to write such statements rigorously is the subject of the specification chapter.
ADT versus the data structure that implements it
Two terms are easy to confuse.
| Term | Answers the question | Example |
|---|---|---|
| Abstract data type | What can I do, and what will happen? | A counter with `increment` and `value` |
| Data structure | How are the items laid out and linked? | An integer field, a list, a linked chain of nodes |
A data structure is a building block. An ADT is a contract, and an implementation uses one or more data structures to honor that contract. The same data structure can implement different ADTs. A Python list can back a stack, a queue, or a set. The same ADT can also be backed by different data structures, as the two counters showed.
If you describe a type by saying "it's a list," you are describing the representation. If you describe it by saying "it records scores by name and computes their average," you are describing the ADT.
Common mistakes
- Treating the first implementation as the definition. If your tests or documentation say "the counter has a
_countfield," you have made one implementation the specification. Anyone who wants to change it must change the "contract" too. - Leaving error behavior out. An ADT whose operation sometimes fails but does not say how leaves clients guessing. Decide whether an empty
average()raises, returnsNone, or returns 0, and write it down. - Assuming a leading underscore enforces privacy. In Python,
_countis a convention. A client can still readcounter._count. The ADT only works if clients agree to stay on the public operations. Later chapters cover how exposing internals breaks this agreement. - Making every operation mirror a field. If your ADT is just a getter and setter for each field, the representation is leaking through the operations. Choose operations that describe what clients want to do, such as
add_score, and not how data is stored.
A quick test for whether you have an ADT
Ask these questions about a type you are designing:
- Can I describe every operation and its result without mentioning how data is stored?
- Could I replace the internal storage tomorrow without editing any client?
- Have I stated what happens for the awkward inputs, such as an empty collection or a missing key?
If all three answers are yes, you have an ADT with at least one implementation. If any answer is no, either the description is incomplete or the representation has leaked into the interface.
Exercise
A teammate writes a Python class Playlist with a public attribute songs (a list). Other modules call playlist.songs.append(title) and len(playlist.songs). Later, the team wants to store songs in a database instead of a list. Explain why this design makes the change hard, and name two operations you would define so that Playlist becomes an ADT.
Show answer
Clients depend directly on the representation: they assume songs is a list that supports append and len. Switching to a database breaks every one of those call sites, so the representation decision is spread across the program. To make Playlist an ADT, define operations that describe intent, such as add_song(title) and count() (others like titles() would also work), and have clients call only those. Then only the Playlist class body knows whether songs live in a list or a database.