Sub topic 1
Why hide details: abstraction and information hiding
Prerequisites
This chapter assumes you can:
- Write Python classes with methods and an
__init__constructor. - Use lists and dictionaries, and know that two variables can refer to the same object.
- Read a function that returns a value or raises an exception.
- Recognize Big-O notation such as O(1) and O(n), which appears briefly near the end.
No earlier chapter is needed. This chapter explains the two ideas the rest of the tutorial depends on: abstraction and information hiding.
The problem: code that knows too much
Suppose you write a small contact book. You store entries in a list of (name, phone) pairs, and you let other code read that list directly.
class LeakyContacts:
def __init__(self):
self.entries = [] # list of (name, phone) pairs
def add(self, name, phone):
self.entries.append((name, phone))
def phone_for(book, name):
for entry_name, phone in book.entries:
if entry_name == name:
return phone
return None
book = LeakyContacts()
book.add("Ada", "555-0100")
print(phone_for(book, "Ada")) # 555-0100This works. It also has a quiet cost. The function phone_for now depends on a fact about the class: that entries is a list of pairs. Lookup by scanning a list takes O(n) time, so you later decide to switch to a dictionary. After that change, every piece of code that loops over book.entries and unpacks pairs is wrong. You must find all of it, in every file, and fix it.
The class and its users are coupled. Coupling means a change in one place forces changes in another. The two ideas below are the standard way to reduce it.
Abstraction
Abstraction means describing a thing by what it does and leaving out how it does it. You use abstractions constantly. You call sorted(items) without knowing which sorting algorithm runs. You press a light switch without knowing the wiring.
An abstraction has two parts:
- What you keep: the details a user needs to use the thing correctly. For
sorted, that is the input, the output, and the promise that the result is in order. - What you drop: the details a user does not need. For
sorted, that is the algorithm, the temporary buffers, and the tie-breaking steps.
For data, the abstraction describes values and the operations on them. A contact book is "something you add a name and phone number to, and ask for a phone number by name." It is not "a list of tuples." The list is one way to build it.
Deciding what to keep is a design choice, and you can get it wrong in two directions. If you keep too little, users cannot do their job. If you keep too much, such as exposing the list, you tie users to details you may want to change.
Information hiding
Information hiding is the practice of keeping the dropped details out of the user's reach. David Parnas described the idea in 1972. He proposed splitting a system into modules so that each module hides one design decision that is likely to change.
Abstraction and information hiding are related but different:
| Idea | What it is | Where it lives |
|---|---|---|
| Abstraction | A simplified description that leaves out detail | In the design and the documentation |
| Information hiding | Blocking access to the left-out detail | In the code structure and the language |
You can have an abstraction without hiding. The leaky contact book above has a clear idea behind it, but the list is open to everyone. You can also hide things badly: if you hide data but your documentation never says what the operations do, users cannot form a correct picture of the class.
When both are present, the code is split into two sides:
- The client is the code that uses the type.
- The implementer is the code that builds the type.
The client relies on a small, stated set of promises. The implementer is free to do anything that keeps those promises.
The same example with details hidden
Here is the contact book again, with the representation made private and a small set of operations offered instead.
class Contacts:
"""A mapping from names to phone numbers.
add(name, phone): record phone for name, replacing any earlier number.
phone_for(name): return the phone for name, or None if name is unknown.
"""
def __init__(self):
self._phones = {}
def add(self, name, phone):
self._phones[name] = phone
def phone_for(self, name):
return self._phones.get(name)
book = Contacts()
book.add("Ada", "555-0100")
print(book.phone_for("Ada")) # 555-0100
print(book.phone_for("Bob")) # NoneThe docstring is the abstraction. The leading underscore on _phones is the hiding. Clients ask for a phone number through phone_for. They never see how it is stored.
If you later find that a dictionary is the wrong choice, say because you need entries kept in insertion order with duplicates allowed, you rewrite the inside of Contacts. Clients that only call add and phone_for keep working without edits.
Notice also a behavior the documentation fixes: calling add twice with the same name replaces the number, and an unknown name returns None. These are part of the promise. An implementation that raised an error for an unknown name would break clients, even though the method names match.
What hiding buys you
- Local change. You can alter a hidden decision and touch only one class. This is the main payoff.
- Less to learn. A client programmer reads two method descriptions, not the whole implementation.
- Fewer ways to break things. If outside code cannot write to
_phones, it cannot put the object into a state the class never meant to allow. - Independent work. Two people can build the client and the implementation at the same time once the operations are agreed on.
What hiding costs, and where it stops
Hiding is not free, and it is not absolute.
- Extra code. You write methods where a plain attribute would do. For a tiny script that nobody will extend, this can be more effort than it saves.
- Possible slowdown. A method call is slightly slower than direct attribute access. This rarely matters, but a hot inner loop may show it.
- Promises you must keep. Everything you document becomes something clients may rely on. Document only what you are willing to maintain. If a doc says "returns results sorted by name," you can never drop that ordering.
- Language limits. Python does not enforce privacy. The single underscore is a convention that tells readers "do not touch this." A determined caller can still write
book._phones. Languages such as Java and C++ haveprivatekeywords that the compiler checks, and even there reflection or pointer tricks can get around them. In practice, hiding is a shared agreement backed, where available, by the language.
Some performance facts also leak through any abstraction. A client that calls phone_for in a loop over a million names cares whether lookup is O(1) or O(n). You usually state the cost as part of the documentation, without revealing the structure that produces it.
Common errors
| Mistake | Why it hurts | Fix |
|---|---|---|
| Public attributes holding the internal data | Clients depend on the layout, so changing it breaks them | Keep data in `_names` and expose operations |
| Documenting how instead of what ("loops over the list") | The implementation detail becomes a promise | Describe results, errors, and effects only |
| Leaving behavior undocumented (empty lookups, duplicates) | Clients guess, and different clients guess differently | State each case in the docstring |
| Hiding the attribute but returning it from a method | The caller still holds the internal object and can change it | Return a copy or an immutable view |
| Exposing an operation per internal step | The interface mirrors the implementation, so it cannot change | Design operations around what clients need to accomplish |
The fourth mistake is subtle enough that a later chapter is devoted to it.
Looking ahead
The contact book has an interface (add, phone_for), a promised behavior, and a hidden representation. An abstract data type, or ADT, is exactly that combination, stated carefully. The next chapters define it, show how to write the promises precisely, and then build one ADT with two different internal structures to prove that clients do not notice the difference.
Exercises
Exercise
A teammate writes a Playlist class with a public attribute songs, a list of titles. Other modules call playlist.songs.append(...) and len(playlist.songs). Describe what goes wrong if the team later wants to store songs in a database instead of a list, and sketch a better design.
Show answer
Every module that touches songs assumes it is an in-memory list, so each one must be rewritten when storage changes. The class and its clients are coupled through the attribute. A better design makes the storage private (_songs) and offers operations such as add_song(title), count(), and titles(). The last should return a copy. Clients call only those operations, so the storage can move to a database by changing the class alone.
Exercise
Is this statement about abstraction or information hiding? "The documentation for Contacts never mentions dictionaries." Then say which of the two the leading underscore on _phones supports.
Show answer
Leaving dictionaries out of the documentation is abstraction, because it drops a detail the client does not need. The leading underscore supports information hiding, because it marks the representation as off limits to clients.
Exercise
The documentation for Contacts.phone_for says it returns None for an unknown name. A new implementer changes it to raise KeyError for unknown names, arguing that the method names and parameters are unchanged. Why is this still a breaking change?
Show answer
Clients were told that an unknown name gives None, so they may test if book.phone_for(n) is None:. With the change, that code raises an exception instead. The promised behavior is part of the interface, not just the method signature.