Replace Derived Variable with Query

Removes smells
Compare
Symptom
Human

A field that mirrors values computed from other fields, updated by hand at multiple write sites — `total` updated every time `items` changes.

Agent

The agent finds a field whose value mirrors a computation on other fields; every writer of the source field must update the derived field consistently or the values drift.

Goal
Human

Values computed from other state are computed on demand; no separate field needs to be kept in sync.

Agent

Derived values are computed on demand; the agent reasons about state by reading source fields and trusting derivations.

Before the refactoring

class Order {
items;
total;
add(item) { this.items.push(item); this.total += item.price; }
}

After the refactoring

class Order {
items;
add(item) { this.items.push(item); }
total() { return this.items.reduce((s, i) => s + i.price, 0); }
}
Example source: Illustrative example written for this site, not a quotation from any source.
Pressure
Human

The derived field can drift from its source; every writer of the underlying field must remember to update the derived one; bugs are 'why is total wrong here?' instead of local.

Agent

The agent must trace every writer of the source field to verify the derived field stays in sync; bugs hide where one writer forgot to update the derivation.

Tradeoff
Human

If the derivation is expensive and the source rarely changes, recomputing on every read may be wasteful — measure before deciding.

Agent

Recomputing on every read can multiply cost if the derivation is expensive and the source rarely changes; the agent verifying performance must measure before deciding.

Relief
Human

Mutation scope shrinks; reasoning about state is simpler; no chance of the derived field drifting from its source.

Agent

Mutation scope shrinks to source fields; the agent reasons about state without modeling derivation update timing; consistency is by construction.

Trap
Human

Replacing every derived value with a query — even ones that wrap an expensive computation called many times per render — substitutes correctness for runtime cost that matters.

Agent

Replacing every derived field with a query — including ones wrapping expensive computations called many times — trades runtime cost for correctness without measuring the impact.