Sub topic 1
Why Hide Details: Abstraction and Information Hiding
Prerequisites
This chapter assumes you can read Python classes and functions, and that you know how lists and exceptions work. It also assumes you know what Big-O notation means for time cost. You do not need to know what an abstract data type is yet. Later chapters define it.
Abstraction: keeping what matters
Abstraction means describing a thing by what it does and leaving out how it does it. When you call sorted(names), you rely on the promise that you get a new sorted list. You do not need to know which algorithm runs inside.
Information hiding is the design rule that makes abstraction hold up. A module keeps its internal decisions private and shows clients only a small public surface. A client is any code that uses the module. If the internal decisions stay private, the module's author can change them later without breaking clients.
A client that knows too much
Here is a small example. A program tracks recent search terms. The first version stores them in a list, and a client reaches into that list directly.
class History:
def __init__(self):
self.items = []
def record(self, term):
self.items.append(term)
history = History()
history.record("python")
history.record("stacks")
# The client depends on the list inside History.
print(history.items[-1])This works. The problem appears when the author wants to change the storage, for example to keep only the 100 most recent terms. A collections.deque with maxlen=100 does that well. After the change, any client that wrote history.items[-1] or history.items.sort() is tied to the old representation, and some of that code may break.
The same module with its details hidden
Now give clients an operation, and keep the storage private.
from collections import deque
class History:
def __init__(self):
self._items = deque(maxlen=100)
def record(self, term):
self._items.append(term)
def latest(self):
if not self._items:
raise IndexError("latest of empty history")
return self._items[-1]
history = History()
history.record("python")
history.record("stacks")
print(history.latest()) # stacksThe client now calls latest() and nothing else. The author switched from a list to a bounded deque, and the client code did not change. The leading underscore on _items is Python's convention for "private". Python does not enforce it, so the hiding depends on clients respecting the convention.
What the boundary looks like
The solid arrows show the allowed path. The dotted arrow shows the shortcut that information hiding rules out. Every shortcut like it is a place where a later change can break a client.
Why this pays off
Hiding details gives you three practical benefits.
- Local change. You can swap the representation, fix a bug, or improve speed in one place.
- Easier reasoning. A client author needs to understand only the operations and their promised behavior, not the internals.
- Protected rules. The module can enforce its own rules, such as "at most 100 items", because no outside code can bypass them.
The cost of hiding
Information hiding adds a layer. Each access goes through a method call, which is slightly slower than reading a field. You must also decide which operations to offer, and a poor choice makes clients awkward. If you provide no way to read the last item, clients will ask for one. Designing a good set of operations is the work that the next chapters take on.
Exercise
A class Inventory stores its products in a public list called products. A client calls inventory.products.sort(). The author wants to replace the list with a dictionary keyed by product ID. Explain why this change is risky, and name one change to the class that would make it safe.
Show answer
A dictionary has no sort() method, so the client's call fails, and any other code that indexes or iterates products as a list may break too. The client depends on the representation. To make the change safe, make the storage private (_products) and offer operations such as add(product) and sorted_products(). Clients then use only those operations, so the author can switch to a dictionary without changing them.