Sub topic 1
Why Hide Details: Abstraction and Information Hiding
Prerequisites
This chapter assumes basic programming with functions, classes, lists, references, and exceptions. You should also know that Big-O notation describes how an operation's cost grows as input size increases.
Abstraction and Information Hiding
An abstraction presents the useful idea while hiding unnecessary details. Information hiding keeps an implementation's internal representation private so clients cannot depend on it.
For example, a stack lets a client add and remove the most recent item. The client does not need to know whether the stack uses a list, a linked chain, or another structure. Hiding that choice makes the implementation easier to replace without changing client code.
What an Abstract Data Type Is
An abstract data type (ADT) is a type defined by its operations and their observable behavior, rather than by its representation. “Abstract” means that the specification describes what the type does, not how it stores data.
A stack ADT has last-in, first-out behavior. If a client pushes a, then b, the next pop returns b. The ADT does not require a particular data structure.
Describing an ADT by Its Operations
Describe an ADT by listing each operation, its signature, and its effect. Operations commonly fall into these categories:
- A constructor creates an instance, such as
Stack(). - A mutator changes the instance, such as
push(item). - An observer returns information without changing the instance, such as
peek(). - A predicate answers a property question, such as
is_empty().
For a stack, pop() removes and returns the top item. peek() returns the top item but leaves the stack unchanged. These descriptions are part of the interface's contract.
Specifying Behavior
A behavioral specification states what clients may assume. A precondition is something that must be true before an operation runs. A result describes its return value and state change. An error case describes what happens when a precondition fails.
For example:
push(x)has no special precondition and addsxto the top.pop()returns and removes the top item. On an empty stack, it raisesIndexError.peek()returns the top item without removing it. On an empty stack, it raisesIndexError.
An axiom is a rule that relates operations. After push(x), pop() returns x, assuming no intervening operation changes the stack. Such rules let implementations be tested without exposing their storage.
Exercise
Why can a client use either a list-based stack or a linked stack?
Show answer
Both implementations satisfy the same operations and behavioral specification, so the client depends on the ADT rather than the representation.