Programming Search⌘K

Techniquecore

Replace derived variable with query

Replace a stored value that the code keeps in step with other data by a function that computes it from that data when asked, so that the two can never disagree.

Family
refactoring
Intent
Compute a value from its source data in place of storing a copy that must be kept up to date.

Purpose

A derived variable stores a value that other data already determines: a total of the items in a cart, a count of the entries in a list, a discounted price. Each change to the source data must also update the derived variable. When one code path forgets, the two disagree, and the bug shows up far from where it was made.

Replace derived variable with query removes the stored copy and computes the value when asked. The catalogue card replaces a _discountedTotal that a setter adjusts with a getter that subtracts the discount from the base total.1 The book treats this as a way to reduce the scope of mutable data, which it calls one of the largest sources of problems in software.2

There is an exception. If the source data cannot change, a derived value computed once from it cannot go stale, and keeping it is safe. The refactoring is for derived values that the code keeps in step by hand.2

Steps

  1. Find each place that updates the variable. If it is updated for different reasons, separate them first with Split Variable.2
  2. Write a function that computes the value from the source data.
  3. Where the variable is read, add an assertion that the variable equals the function's result. See Introduce Assertion. Test.2
  4. Replace each read of the variable with a call to the function. Test.
  5. Delete the variable and the code that updated it, with Remove Dead Code. Test.

Step 3 is the check: if the assertion fails in the tests, the stored value was already wrong somewhere, and you have found a bug.

Example

A cart stores its total and updates it in add. A remove added later forgot to update it. The assertion of step 3 finds the bug, and the query fixes it by construction.

import assert from "node:assert/strict";

class CartBefore {
  items = [];
  totalCents = 0;
  add(name, cents) { this.items.push({ name, cents }); this.totalCents += cents; }
  remove(name) { this.items = this.items.filter((i) => i.name !== name); } // forgot the total
}

class Cart {
  #items = [];
  add(name, cents) { this.#items.push({ name, cents }); }
  remove(name) { this.#items = this.#items.filter((i) => i.name !== name); }
  get totalCents() { return this.#items.reduce((s, i) => s + i.cents, 0); }
}

const before = new CartBefore();
before.add("tea", 350); before.add("cake", 400); before.remove("cake");
const query = before.items.reduce((s, i) => s + i.cents, 0);
assert.notEqual(before.totalCents, query); // the step 3 check finds the stale copy

const cart = new Cart();
cart.add("tea", 350); cart.add("cake", 400); cart.remove("cake");
assert.equal(cart.totalCents, 350);
console.log("replace derived variable with query: tests pass");
Output
replace derived variable with query: tests pass

The cart now has one fact, its items, and the total cannot disagree with them.

Language What the example shows
JavaScript a stored total replaced by a getter, after the step 3 check finds a stale copy, as above
Python the same change with a property, and functools.cached_property for an object whose items cannot change
Go the same change with a method; the slice of items is the only state
PythonGitHub
from dataclasses import dataclass, field
from functools import cached_property


@dataclass
class Cart:
    items: list[tuple[str, int]] = field(default_factory=list)

    def add(self, name: str, cents: int) -> None:
        self.items.append((name, cents))

    def remove(self, name: str) -> None:
        self.items = [i for i in self.items if i[0] != name]

    @property
    def total_cents(self) -> int:  # computed, never stored
        return sum(c for _, c in self.items)


cart = Cart()
cart.add("tea", 350)
cart.add("cake", 400)
cart.remove("cake")
assert cart.total_cents == 350


# When the source data cannot change, computing once and keeping it is safe.
@dataclass(frozen=True)
class Receipt:
    lines: tuple[int, ...]

    @cached_property
    def total_cents(self) -> int:
        return sum(self.lines)


r = Receipt((350, 400))
assert r.total_cents == 750 and r.total_cents == 750
print("replace derived variable with query: tests pass")
Output
replace derived variable with query: tests pass
package main

import "fmt"

type Item struct {
	Name  string
	Cents int
}

// Cart keeps only its items; the total is computed when asked.
type Cart struct{ items []Item }

func (c *Cart) Add(name string, cents int) { c.items = append(c.items, Item{name, cents}) }

func (c *Cart) Remove(name string) {
	kept := c.items[:0]
	for _, it := range c.items {
		if it.Name != name {
			kept = append(kept, it)
		}
	}
	c.items = kept
}

func (c *Cart) TotalCents() int {
	total := 0
	for _, it := range c.items {
		total += it.Cents
	}
	return total
}

func main() {
	var c Cart
	c.Add("tea", 350)
	c.Add("cake", 400)
	c.Remove("cake")
	if c.TotalCents() != 350 {
		panic(c.TotalCents())
	}
	fmt.Println("replace derived variable with query: tests pass")
}
Output
replace derived variable with query: tests pass

When to use

  • A value that other data determines. If you can compute it, you do not have to store it.
  • Code that keeps two things in step. Every place that updates the source must also update the copy. That is where bugs come from.
  • A bug where a total or a count is wrong. Replace the copy with a query, and the class of bug goes away.

Pitfalls

Cost. Computing the value each time can be slow when the data is large and the value is read often. Measure first. If the cost matters, cache the result and clear the cache in the one place that changes the source data.

Data that cannot change. When the source data is immutable, a value derived from it once does not go stale, and the refactoring is not needed.2

Derived data across systems. A copy in another service or a database table is not one variable. Removing it is a data migration, and the readers may be outside your code.

Tools that do it

This refactoring is a sequence of steps, not one action of a tool. The assertion of step 3, run by the test suite, is the check that the change is safe.

References

  1. Martin Fowler, Catalog of Refactorings, Replace Derived Variable with Query, the entry
  2. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 9, Organizing Data, Replace Derived Variable with Query, motivation and mechanics; Chapter 3, Bad Smells in Code, Mutable Data

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • at least three sources