Encapsulation
Twice this month, Shelfwise showed a book with −2 copies in stock. Somewhere, some piece of code wrote book.stock = book.stock - 3 without checking first. Fourteen different places write to stock, and every one of them was trusted to remember the rule. Encapsulation removes that trust problem.
The rule
Hide the state; expose only operations that keep the rules.
Encapsulation has two halves:
- Hide an object's data so outside code cannot change it directly.
- Expose a small set of methods, and put the rules inside them.
class Book:
def __init__(self, title, stock):
self.title = title
self._stock = stock
@property
def stock(self):
return self._stock # anyone may read it
def reserve(self, qty):
if qty <= 0 or qty > self._stock:
raise ValueError("Cannot reserve that many copies")
self._stock -= qty
def restock(self, qty):
if qty <= 0:
raise ValueError("Restock amount must be positive")
self._stock += qtyNow the rule "stock never goes negative" lives in one place. Fourteen callers become fourteen calls to reserve(), and none of them can break the rule however they are written.
Languages enforce hiding differently. Java and C# have private and public keywords that the compiler checks. Python relies on convention: a leading underscore (_stock) means "internal, do not touch from outside". Either way, the design idea is the same.
Some fields have the strictest rule of all: never change after creation. A book's ISBN or an order's ID should be set once in the constructor and only ever read. Expose them as read-only properties with no method that alters them, and a whole family of "who changed the ID?" bugs disappears.
Encapsulation also frees you to change the inside later. If Shelfwise starts storing stock per warehouse, only Book changes; every caller still just calls reserve(qty).