Sub topic 14
Representation Exposure and How to Prevent It
This chapter assumes you can read Python classes, know that lists are mutable and passed by reference, and have seen a representation invariant (a condition every valid internal state must satisfy). Here you will see how callers can break that invariant from outside, and how to stop them.
What representation exposure is
Representation exposure happens when code outside a class can reach the data that represents the abstract value, and can change it without using the class's operations. The class then cannot protect its invariant or keep its promises, and clients start to depend on the representation.
Python does not enforce privacy. The leading underscore in _names is only a convention. Exposure is therefore a design problem you prevent by what your methods accept and return.
A leaking observer
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']LeakyRoster.names() returns the same list object it stores. The caller calls clear() on that list, and the roster changes although add was never called. Returning list(self._names) gives the caller a separate list, so changes to it do not reach the roster.
Why it breaks the invariant
Consider IntSet from the earlier chapter, whose invariant is that _items has no duplicates. Suppose we add this method:
def items(self):
return self._itemsA client can then call s.items().append(3) twice. The list now holds duplicates, and size() returns the wrong answer. No _check_rep call runs, because the client never called an IntSet operation. The invariant can only be checked at the class's own boundaries, so exposure defeats it.
Exposure through inputs
Exposure also happens on the way in. If a constructor stores a list the caller passed, the caller still holds a reference to it.
class Team:
def __init__(self, members):
self._members = list(members) # copy on the way in
def members(self):
return list(self._members) # copy on the way outWithout the copy in __init__, a later members.append("x") by the caller would change the team.
Ways to prevent it
- Copy on the way in and on the way out (defensive copying), as above.
- Return immutable values, such as a
tupleorfrozenset, so there is nothing to modify. - Return a view or iterator instead of the structure, when copying is too costly.
- Do not store references to mutable arguments unless the specification says the class owns them.
Copying has a cost. list(self._names) takes O(n) time, while returning the internal list took O(1). Choose deliberately, and state the choice in the specification.
Checklist
| Question | Exposure if the answer is yes |
|---|---|
| Does a method return a mutable field directly? | Output leak |
| Does a constructor or mutator store a mutable argument directly? | Input leak |
| Does a client-visible object hold a reference into the internals? | Aliasing leak |
Exercise
A class Playlist stores songs in self._songs (a list). Its constructor is def __init__(self, songs): self._songs = songs, and def songs(self): return self._songs. Name both leaks and give the fix for each.
Show answer
The constructor leaks on input because the caller keeps a reference to the same list and can change it later. The songs method leaks on output because it hands out the internal list. Fix them with self._songs = list(songs) in the constructor and return list(self._songs) in songs, or return a tuple.