Concept

Encapsulate What Varies

Definition

Encapsulate what varies is the design heuristic that says: find the aspects of your system that are likely to change, and isolate each behind a stable interface, so the rest of the code depends on the unchanging interface rather than the changing detail. Variation is then local — confined to one swappable place — instead of smeared across every part that touches it.

The heuristic is the unifying idea behind nearly every design pattern. Each pattern names a particular kind of variation and gives it a home: an object's creation, the algorithm it uses, the structure it is composed into, the way it responds to events. Once a varying concern is encapsulated, you can add a new variant without editing the existing code that uses it — the hallmark of a design that is open to extension but closed to disruptive modification.

Why it matters

How it works

Spot the axis of change

Start by predicting what is likely to vary: the payment method, the sorting algorithm, the export format, the notification channel. Each of these is an axis of change. The mistake is to scatter conditionals for these variations throughout the code; the fix is to name the axis as an abstraction and give it one interface.

Put a stable interface in front of it

Define an interface that captures what the varying part does, not how. Then express each variant as a separate object that conforms to that interface, and have the rest of the system depend only on the interface. This is exactly programming to an interface rather than an implementation — new variants plug in without the client ever knowing they exist.

Patterns as catalogued encapsulations

Most patterns are this heuristic applied to a specific axis. Strategy encapsulates a varying algorithm; Factory encapsulates varying object creation; Decorator encapsulates varying added responsibilities; Observer encapsulates a varying set of reactions. Learning to see the axis of change is what lets you reach for the right pattern instead of guessing.

Where it goes next

Continue exploring

Tags