Programming Search⌘K

Techniquecore

Change value to reference

Also called share one object, use a repository for shared objects.

When many copies of one logical object exist, and an update to it must be seen by all holders, keep one shared object for it in a repository, and give each holder a reference to that object.

Family
refactoring
Intent
Keep one object for one thing, and let every holder refer to it.

Purpose

When each order makes its own customer object from the data it was given, ten orders for one customer hold ten copies. As long as nobody changes a customer, that is fine. When the customer's address changes, each copy must be found and changed, or the copies disagree.

Change value to reference keeps one object for each customer, and gives each order a reference to it. The catalogue card replaces a constructor call, new Customer(customerData), with a lookup in a repository by the customer's id.1 The refactoring is in both editions of the book.23 The repository is the one place that makes and holds the shared objects. See Repository pattern.

Steps

  1. Make a repository for the objects, if there is none.3
  2. Make sure that each object has an id that the repository can look it up by, and that the constructor can get the right object for an id.
  3. Change each place that makes an object of the type to get it from the repository. Test after each change.

Example

Two orders for one customer each make their own Customer. An update to the email of one copy does not reach the other. After the refactoring, both orders get the customer from a repository, and see one update.

import assert from "node:assert/strict";

class Customer {
  constructor(id, email) { Object.assign(this, { id, email }); }
}

// Before: each order makes its own copy.
class OrderBefore {
  constructor(data) { this.customer = new Customer(data.customerId, data.email); }
}
const o1 = new OrderBefore({ customerId: "c1", email: "old@example.org" });
const o2 = new OrderBefore({ customerId: "c1", email: "old@example.org" });
o1.customer.email = "changed@example.org";
assert.equal(o2.customer.email, "old@example.org"); // the copies disagree

// After: one object for each id, in a repository.
class CustomerRepository {
  #byId = new Map();
  register(id, email) {
    if (!this.#byId.has(id)) this.#byId.set(id, new Customer(id, email));
    return this.#byId.get(id);
  }
  get(id) {
    const c = this.#byId.get(id);
    if (!c) throw new Error(`no customer ${id}`);
    return c;
  }
}
class Order {
  constructor(data, repo) { this.customer = repo.get(data.customerId); }
}

const repo = new CustomerRepository();
repo.register("c1", "old@example.org");
const o3 = new Order({ customerId: "c1" }, repo);
const o4 = new Order({ customerId: "c1" }, repo);
o3.customer.email = "changed@example.org";
assert.equal(o4.customer.email, "changed@example.org");
assert.equal(o3.customer, o4.customer); // one object
console.log("change value to reference: tests pass");
Output
change value to reference: tests pass

The repository here is a map in memory. In a larger program, it can load the objects from a database the first time they are asked for.

Language What the example shows
JavaScript a repository class that keeps one object for each id, as above
Python a repository with a dictionary, and a check with is that two orders hold the same object
Java a repository with computeIfAbsent, and == to show one object
Go a repository that hands out pointers, so that each order refers to one struct
PythonGitHub
class Customer:
    def __init__(self, cid: str, email: str) -> None:
        self.id, self.email = cid, email


class CustomerRepository:
    def __init__(self) -> None:
        self._by_id: dict[str, Customer] = {}

    def register(self, cid: str, email: str) -> Customer:
        return self._by_id.setdefault(cid, Customer(cid, email))

    def get(self, cid: str) -> Customer:
        return self._by_id[cid]


class Order:
    def __init__(self, customer_id: str, repo: CustomerRepository) -> None:
        self.customer = repo.get(customer_id)


repo = CustomerRepository()
repo.register("c1", "old@example.org")
a = Order("c1", repo)
b = Order("c1", repo)
a.customer.email = "changed@example.org"
assert b.customer.email == "changed@example.org"
assert a.customer is b.customer
print("change value to reference: tests pass")
Output
change value to reference: tests pass
JavaGitHub
import java.util.HashMap;
import java.util.Map;

public class Main {
    static final class Customer {
        final String id;
        String email;
        Customer(String id, String email) { this.id = id; this.email = email; }
    }

    static final class CustomerRepository {
        private final Map<String, Customer> byId = new HashMap<>();
        Customer register(String id, String email) {
            return byId.computeIfAbsent(id, k -> new Customer(k, email));
        }
        Customer get(String id) {
            Customer c = byId.get(id);
            if (c == null) throw new IllegalArgumentException("no customer " + id);
            return c;
        }
    }

    record Order(Customer customer) {}

    public static void main(String[] args) {
        CustomerRepository repo = new CustomerRepository();
        repo.register("c1", "old@example.org");
        Order a = new Order(repo.get("c1"));
        Order b = new Order(repo.get("c1"));
        a.customer().email = "changed@example.org";
        if (!b.customer().email.equals("changed@example.org")) throw new AssertionError("update");
        if (a.customer() != b.customer()) throw new AssertionError("identity");
        System.out.println("change value to reference: tests pass");
    }
}
Output
change value to reference: tests pass
package main

import "fmt"

type Customer struct {
	ID    string
	Email string
}

// CustomerRepository hands out pointers, so each order refers to one struct.
type CustomerRepository struct {
	byID map[string]*Customer
}

func (r *CustomerRepository) Register(id, email string) *Customer {
	if c, ok := r.byID[id]; ok {
		return c
	}
	c := &Customer{id, email}
	r.byID[id] = c
	return c
}

func (r *CustomerRepository) Get(id string) (*Customer, error) {
	c, ok := r.byID[id]
	if !ok {
		return nil, fmt.Errorf("no customer %s", id)
	}
	return c, nil
}

type Order struct{ Customer *Customer }

func main() {
	repo := &CustomerRepository{byID: map[string]*Customer{}}
	repo.Register("c1", "old@example.org")
	c, err := repo.Get("c1")
	if err != nil {
		panic(err)
	}
	a, b := Order{c}, Order{c}
	a.Customer.Email = "changed@example.org"
	if b.Customer.Email != "changed@example.org" || a.Customer != b.Customer {
		panic("not shared")
	}
	if _, err := repo.Get("c9"); err == nil {
		panic("expected an error")
	}
	fmt.Println("change value to reference: tests pass")
}
Output
change value to reference: tests pass

When to use

  • An update that every holder must see. A customer's address, a product's price, an account's status.
  • Many copies of large data. One shared object can also save memory, but the reason for the refactoring is the update.
  • Identity matters. When two objects with the same data are still two different things, they are entities, not values. See Value equality and identity.

Pitfalls

Shared mutable state. A reference that many holders share can be changed by any of them. That is the point of the refactoring, and also its risk: a change in one part of the program has effects in others. If nothing must be updated, a value is safer. See Change Reference to Value.1

A repository that is global data. A repository that any code can reach is a kind of global data. Pass it to the code that needs it, as the example does.

Concurrency. If several threads share the object, its updates need synchronization.

Tools that do it

This refactoring is a sequence of steps, not one action of a tool.

References

  1. Martin Fowler, Catalog of Refactorings, Change Value to Reference, the entry; inverse of Change Reference to Value
  2. Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 8, Organizing Data, Change Value to Reference
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 9, Organizing Data, Change Value to Reference, motivation, mechanics and the example of orders and customers

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)
WritingW4 complete
  • a review of the text: no review record reviews/R1CFJN/text.yaml