Replace Derived Variable with Query

Removes smells
Symptom

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

Goal

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

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

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.

Tradeoff

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

Relief

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

Trap

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.