Encapsulate Record

Compare
Symptom
Human

A plain object passed around the codebase whose fields are read and written by anyone — `org.name = '...'` from any consumer.

Agent

A plain object passed across the codebase; the agent reading any consumer must inspect every other consumer to learn what shape the record actually has.

Goal
Human

A bare record (plain object with public fields) becomes a class whose properties are accessed through methods that can validate, log, or derive.

Agent

The record is a class with accessors; the agent reasons about its shape, invariants, and behavior in one definition.

Before the refactoring

const org = { name: 'Acme', country: 'US' };
console.log(org.name);

After the refactoring

class Org {
constructor({ name, country }) { this._name = name; this._country = country; }
name() { return this._name; }
country() { return this._country; }
}
console.log(new Org(org).name());
Example source: Illustrative example written for this site, not a quotation from any source.
Pressure
Human

Field renames touch every reader/writer; validation can't be enforced; the record's invariants drift as consumers diverge in their assumptions.

Agent

Field changes ripple through every consumer; the agent must coordinate updates and verify each consumer respects the (implicit) contract.

Tradeoff
Human

Wrapping every record adds ceremony — only worth it when behavior or validation will accrete around the data.

Agent

Wrapping every record adds construction ceremony at every entry; for records without invariants or behavior to attract, the agent gains nothing for the per-call cost.

Relief
Human

Field renames stay internal; invariants can be enforced on every read or write; the record becomes a real domain object.

Agent

Field accesses run through named methods; a field rename touches one class definition without changing any caller, and invariants enforced in those methods catch invalid combinations the field-level access would otherwise let through.

Trap
Human

Wrapping every record on principle — even ones with no validation needs, no derivation, no behavior to attract — adds construction ceremony at every entry point.

Agent

Wrapping records on principle without invariants or behavior to add creates classes the agent must instantiate everywhere with no encapsulation gain.