Encapsulate Variable

Symptom

A module-level variable or shared mutable state read and written directly from any consumer — no central audit point for changes.

Goal

All reads and writes pass through a small named function that owns validation, logging, and invariants.

Before the refactoring

let defaultOwner = { firstName: 'Martin', lastName: 'Fowler' };

After the refactoring

let _defaultOwner = { firstName: 'Martin', lastName: 'Fowler' };
function defaultOwner() { return _defaultOwner; }
function setDefaultOwner(o) { _defaultOwner = o; }
Example source: Illustrative example written for this site, not a quotation from any source.
Pressure

Adding validation, logging, or invariant checks requires touching every consumer; bugs from concurrent mutation hide in the gaps; the variable's lifetime is implicit.

Tradeoff

Adds a layer of indirection that pays off only when every access goes through the wrapper — leakage of direct access undoes the benefit.

Relief

A bug fix or audit becomes a one-line addition inside the wrapper; consumers never need to change.

Trap

Adding a getter/setter wrapper without removing the direct access — adds indirection ceremony while consumers still bypass the wrapper, so the encapsulation provides no real guarantee.