Abstraction: hide the data structure
Change how a class stores its data without touching the code that uses it.
Watch the narrated video
Every step
Problem
Steps 1–3Refactor
Steps 4–8Payoff
Steps 9–10Recap
Steps 11–12The code: before and after
Before
class Warehouse:
def __init__(self) -> None:
self.stock: dict[str, int] = {}
def restock(w: Warehouse, sku: str, qty: int) -> None:
w.stock[sku] = w.stock.get(sku, 0) + qty
def pick_order(w: Warehouse, sku: str, qty: int) -> None:
have = w.stock.get(sku, 0)
if have >= qty:
w.stock[sku] = have - qty
def print_report(w: Warehouse, sku: str) -> None:
left = w.stock.get(sku, 0)
print(f"{sku}: {left}")
def main() -> None:
w = Warehouse()
restock(w, "TEA-1", 20)
restock(w, "TEA-1", 10)
pick_order(w, "TEA-1", 15)
print_report(w, "TEA-1") # TEA-1: 15
if __name__ == "__main__":
main()After
class Warehouse:
def __init__(self) -> None:
self._stock: dict[str, deque[int]] = {}
def receive(self, sku: str, qty: int) -> None:
self._stock.setdefault(sku, deque()).append(qty)
def pick(self, sku: str, qty: int) -> bool:
if self.quantity(sku) < qty:
return False
queue = self._stock.get(sku, deque())
while qty > 0:
oldest = queue.popleft()
used = min(oldest, qty)
if oldest > used:
queue.appendleft(oldest - used)
qty -= used
return True
def quantity(self, sku: str) -> int:
return sum(self._stock.get(sku, deque()))
def deliveries(self, sku: str) -> tuple[int, ...]:
return tuple(self._stock.get(sku, deque()))
def restock(w: Warehouse, sku: str, qty: int) -> None:
w.receive(sku, qty)
def pick_order(w: Warehouse, sku: str, qty: int) -> None:
w.pick(sku, qty)
def print_report(w: Warehouse, sku: str) -> None:
left = w.quantity(sku)
print(f"{sku}: {left}")
def main() -> None:
w = Warehouse()
restock(w, "TEA-1", 20)
restock(w, "TEA-1", 10)
pick_order(w, "TEA-1", 15)
print_report(w, "TEA-1") # TEA-1: 15
print(w.deliveries("TEA-1")) # (5, 10)
if __name__ == "__main__":
main()Transcript, step by step
Problem
Step 1: A shop's warehouse stock Before
A small shop's warehouse keeps its stock in a dict, from product code to quantity. Restock adds a delivery to the dict, pick order takes items out when there are enough, and print report shows what's left. Two deliveries of tea come in, 20 and then 10, and after 15 are picked, the report prints 15.
Step 2: Oldest delivery first Code smell
The tea goes stale, so picking must take the oldest delivery first, and ops need the stock kept per delivery. The quick way turns each value in the dict into a deque of delivery quantities. Restock now appends to the deque, and pick order sums it, then takes from the front in a loop. Print report sums the deque too, and the run still prints 15.
Step 3: Every caller knows the dict Code smell
Every caller works on the dict directly, so each one depends on how the warehouse stores its stock. Restock uses the dict here, pick order here, and the report here. One change to the storage meant rewriting three functions that only wanted to receive, pick and count. The sum over the deque now exists twice, once in pick order and once in print report. And when the stock moves to a database next year, all three get rewritten again.
Refactor
Step 4: Refactor first Back it out
Let's take the deque out again. We'll refactor first, so that the warehouse owns its stock, and then we'll change the storage in one place.
Step 5: Receive moves in Move Method
First, the update moves into Warehouse, as a method called receive. Restock now calls receive on the warehouse, and it no longer touches the dict.
Step 6: Pick moves in Move Method
The check and the update move in next, as pick, which returns true when there was enough stock. Pick order calls pick on the warehouse, and the run still prints 15.
Step 7: Quantity moves in Move Method
The lookup moves in last, as quantity, which returns zero for a product the warehouse has never seen. Print report asks the warehouse for the quantity, and then prints it.
Step 8: Mark the dict private Encapsulate Collection
No caller touches the dict any more, so it gets a leading underscore, which tells readers it's private to the class. Python doesn't stop anyone from reading it, but no code outside Warehouse needs to. That's abstraction, where callers use what the warehouse does, receive, pick and quantity, and never see how it stores the stock. Encapsulation hides a single field, and abstraction goes one step further, because it hides how a whole collection is stored.
Payoff
Step 9: Keep stock per delivery Substitute Algorithm
Now the change request comes back, and this time it stays inside Warehouse. The private dict now holds a deque of deliveries per product, and receive appends to it. Quantity sums the deque, and pick checks the quantity, then takes from the oldest delivery first. Each method keeps its signature and gets a new body, and that move is called Substitute Algorithm. The three functions didn't change, and main gains one line that prints the deliveries as a tuple, a copy that callers can't change.
Step 10: One class knows the storage Payoff
The dict calls are gone from the callers, so restock calls receive here, pick order calls pick here, and the report calls quantity here. The sum over the deque is written once, in quantity, and pick reuses it for its check. The 15 picked came out of the oldest delivery of 20, so 5 of that one are left, next to the newer 10. The three callers depend only on receive, pick and quantity, so changing how Warehouse stores the stock stayed inside Warehouse.
Recap
Step 11: Where we started, where we ended Before / after
On the left, the stock is a plain dict, and all three functions call dict methods on it. On the right, the dict is private and holds a deque per product, behind receive, pick and quantity. A caller like pick order makes one call, and the warehouse decides which delivery the items come from.
Step 12: When to reach for it Takeaways
Reach for it when several functions or classes read or change one collection, and the way it's stored may change. Skip it when one short function owns the dict and nothing outside reads it, because methods around it add lines and hide nothing. You'll spot the need by get or setdefault on another object's dict, or by the same lookup copied into several functions. Python's own deque works this way, because you call append and pop left, and it manages its hidden blocks by itself.