Sub topic 14
Representation exposure and how to prevent it
This chapter assumes you know what an abstract data type (ADT) is, the difference between an interface and an implementation, and what a representation invariant is. It uses Python. You should be comfortable with lists, references, and exceptions.
What representation exposure is
An ADT hides its representation. Clients call operations and never touch the stored data directly. Representation exposure happens when a client gets a way to read or change the representation without going through those operations.
Exposure breaks two promises at once:
- Invariant safety. The class can no longer guarantee its representation invariant, because outside code can modify the data.
- Representation independence. Clients can start to depend on the internal structure. Changing the representation then breaks them.
The second problem is easy to miss. A client that gets back the internal list may start to rely on it being a list. Later you switch to a linked chain of nodes, and that client breaks, even though the ADT's specification did not change.
Exposure through a returned reference
The simplest leak is an observer that returns the internal object. This example comes from the chapter's running code.
class LeakyRoster:
def __init__(self):
self._names = []
def add(self, name):
self._names.append(name)
def names(self):
return self._names # exposes the internal list
class SafeRoster(LeakyRoster):
def names(self):
return list(self._names) # returns a copy
roster = LeakyRoster()
roster.add("Ada")
roster.names().clear()
print(roster.names()) # [] because the caller emptied the internal list
safe = SafeRoster()
safe.add("Ada")
safe.names().clear()
print(safe.names()) # ['Ada']In LeakyRoster, names() returns the same list object the roster stores. The call roster.names().clear() empties the roster without ever calling a roster operation. In SafeRoster, names() returns a new list, so the caller can do anything to it and the roster is unaffected.
The leading underscore on _names does not help here. It is a naming convention that tells readers the attribute is private. Python does not enforce it. The leak comes from handing out a reference, not from the attribute name.
Exposure and the representation invariant
Exposure matters most when the class has an invariant that its own methods maintain. Recall IntSet, whose invariant is that _items contains no duplicates. Suppose we add this method:
class IntSet:
"""A set of integers.
Abstraction function: the list [a, b, c] represents the set {a, b, c}.
Representation invariant: _items contains no duplicates.
"""
def __init__(self):
self._items = []
self._check_rep()
def _check_rep(self):
assert len(self._items) == len(set(self._items))
def add(self, x):
if x not in self._items:
self._items.append(x)
self._check_rep()
def contains(self, x):
return x in self._items
def size(self):
return len(self._items)
def elements(self):
return self._items # BUG: exposes the representation
s = IntSet()
s.add(1)
s.elements().append(1) # no add(), so no check, and now there is a duplicate
print(s.size()) # 2, but the set {1} has size 1add is careful never to insert a duplicate, and it checks the invariant afterward. None of that helps. A client appends 1 to the list returned by elements(), and size() now reports 2 for the set {1}. The invariant is broken, and _check_rep never ran, because no IntSet method was called.
The fix is the same as before: return a copy.
def elements(self):
return list(self._items)This shows why the invariant and exposure belong together. An invariant is only a guarantee if every change to the representation goes through code that preserves it. Exposure creates a path that skips that code.
Exposure through constructor arguments
Exposure also happens on the way in. If a constructor stores a mutable argument without copying it, the caller keeps a reference to the representation.
class Team:
def __init__(self, members):
self._members = members # BUG: stores the caller's list
def size(self):
return len(self._members)
people = ["Ada", "Grace"]
team = Team(people)
people.append("Alan")
print(team.size()) # 3, though no Team operation was calledThe caller's list and the team's list are the same object. Any later change by the caller changes the team. The fix is to copy on the way in:
class Team:
def __init__(self, members):
self._members = list(members)
def size(self):
return len(self._members)The rule is symmetric. Do not hand out references to your mutable representation, and do not keep references that someone else handed you.
Shallow copies and nested mutable data
A copy made with list(...) is shallow. It creates a new outer list, but the elements inside are the same objects. If those elements are themselves mutable, the leak remains one level down.
class Schedule:
def __init__(self):
self._days = {} # maps a day name to a list of events
def add_event(self, day, event):
self._days.setdefault(day, []).append(event)
def events(self, day):
return list(self._days.get(day, [])) # copies the inner list: safe
def all_days(self):
return dict(self._days) # shallow: inner lists are still shared
sched = Schedule()
sched.add_event("Mon", "standup")
sched.all_days()["Mon"].clear()
print(sched.events("Mon")) # [] because the inner list was sharedevents is safe because it copies the list that holds the events, and the events are strings, which cannot be changed. all_days copies only the dictionary. Its values are the internal lists, so a client can empty them.
You have three ways to fix this:
- Deep copy. Use
copy.deepcopyor build the nested structure by hand. This is correct but costs time and memory in proportion to the whole structure. - Return immutable values. Build a new structure out of tuples, which cannot be changed, such as
{day: tuple(events) for day, events in self._days.items()}. - Do not return the structure at all. Offer narrower operations such as
events(day)anddays()that expose only what clients need.
The third option is often best. It keeps the specification small, so there is less to leak and fewer promises to keep.
Defenses
The table summarizes the common defenses and what each costs.
| Defense | How it works | Cost |
|---|---|---|
| Defensive copy | Copy mutable data on the way in and on the way out | Time and memory for each call |
| Immutable representation | Store tuples, strings, or frozen objects that cannot be changed | May need a different design for mutators |
| Immutable view | Return a read-only wrapper, such as `types.MappingProxyType` for dicts | Cheap, but the view reflects later changes to the data |
| Narrow interface | Offer operations that return single values or new objects | More operations to write |
| Document the exposure | State in the specification that the caller must not modify the result | Relies on every client following the rule |
Two points about this table.
First, a read-only view is not a snapshot. If the class later changes its internal dictionary, the view shows the change. That is acceptable if the specification says so and a surprise if it does not.
Second, documenting an exposure is a legitimate choice when a copy is too expensive, for example when elements() is called inside a hot loop on a very large collection. Treat it as a trade-off you made on purpose and wrote down, not as a default.
Where exposure hides
When you review a class, look at every place a reference crosses the boundary of the ADT.
The diagram below shows the boundary and the two directions a reference can cross it.
Check these places:
- Constructor and mutator arguments that are stored directly.
- Observer return values that are, or contain, internal objects.
- Iterators and generators that walk the internal structure while the client can still change it.
- Callbacks or default arguments that hold a reference to internal state.
- Class-level mutable defaults, which are shared by every instance. A definition like
def __init__(self, items=[])stores one list that all instances use.
Iterators deserve a note. Returning iter(self._items) does not give the client the list, but it does tie the client's loop to the live representation. If the class changes the list during the loop, the behavior is undefined by your specification. Either state a rule such as "do not modify the collection while iterating," or iterate over a copy.
Immutable ADTs avoid the problem
An immutable ADT has no mutators. Once created, its value never changes, so sharing a reference is safe as long as the representation itself cannot be changed.
class Point:
def __init__(self, x, y):
self._coords = (x, y) # a tuple cannot be changed
def x(self):
return self._coords[0]
def y(self):
return self._coords[1]
def coords(self):
return self._coords # safe: the caller gets an immutable tuple
p = Point(3, 4)
print(p.coords()) # (3, 4)Returning self._coords is fine here, because tuples of numbers cannot be modified. The same method would be a leak if _coords were a list. Immutability must hold all the way down: a tuple that contains a list is still exposed through that list.
Catching exposure with tests
Tests written against the specification can catch exposure. After getting a value from an observer, modify it, then check that the ADT still behaves as specified.
def check_no_exposure(make_roster):
r = make_roster()
r.add("Ada")
r.names().clear()
assert r.names() == ["Ada"], "observer exposed the internal list"
source = ["Ada"]
# for classes that accept a list in the constructor, also mutate the input
return source
check_no_exposure(SafeRoster)
try:
check_no_exposure(LeakyRoster)
except AssertionError as error:
print("caught:", error)The test passes for SafeRoster and fails for LeakyRoster. It treats the roster as a black box and checks only the promise that mutating a returned value does not change the ADT. Run it against every implementation of the ADT, as you would any other specification check.
Summary of rules
- Treat every reference that crosses the ADT boundary as a possible leak, in both directions.
- Copy mutable inputs when you store them, and copy mutable outputs when you return them.
- Remember that a copy of a container does not copy what the container holds.
- Prefer immutable representations, and keep them immutable all the way down.
- When you skip a copy for cost, write that choice in the specification.
- Test by mutating what the ADT gives you and checking that the ADT is unchanged.
Exercise
A class Playlist stores songs in self._songs, a list of Song objects, where each Song has a mutable title attribute. Its method songs() returns list(self._songs). A client calls playlist.songs()[0].title = "X". Does this change the playlist's contents? Is the representation exposed, and how would you fix it?
Show answer
Yes, the change shows up in the playlist. list(self._songs) is a shallow copy, so the new list holds the same Song objects, and changing one object's title changes it for the playlist too. The representation is exposed one level down. To fix it, make Song immutable (for example, a frozen dataclass or a class with no setters), or return copies of each song, or return only the titles as strings. Making Song immutable is usually the simplest choice.
Exercise
Counter stores its history in self._history = [] and has a constructor __init__(self, history=[]) that does self._history = history. Name two separate representation problems and write a corrected constructor.
Show answer
First, the default argument [] is created once and shared by every Counter built without an argument, so all those instances share one list. Second, even when a caller passes a list, the constructor stores that same list, so the caller can change the counter's state later. A corrected constructor is def __init__(self, history=None): self._history = list(history) if history is not None else [].