Programming Search⌘K

Techniquecore

Preserve whole object

Pass the whole object to a function instead of several values that the caller reads out of that object first.

Family
refactoring
Intent
Let the function take the record that its values come from.

Purpose

Some callers read two or more values out of one object and pass them to a function. Each caller repeats the same reads. If the function later needs a third value from the same object, each caller and the signature must change.

Preserve whole object passes the object itself. The function reads the values that it needs. The catalogue card reads low and high out of aRoom.daysTempRange and calls aPlan.withinRange(low, high). After the refactoring, the call is aPlan.withinRange(aRoom.daysTempRange).1

Steps

  1. Make a new function with the parameter that you want: the whole object. Give it a temporary name.
  2. Write the body of the new function as a call to the old function. Read each old argument out of the object.
  3. Change each caller to call the new function. Test after each change. The reads in the caller are now dead code, so remove them.
  4. Inline the old function into the new one, and give the new function the old name.

Example

A heating plan checks if a room stayed inside a range. Each caller reads low and high from the range of the room. After the refactoring, the plan takes the range.

import assert from "node:assert/strict";

const room = { name: "lab", daysTempRange: { low: 18, high: 23 } };
const plan = { low: 16, high: 24 };

function withinRangeBefore(aPlan, bottom, top) {
  return bottom >= aPlan.low && top <= aPlan.high;
}

function withinRange(aPlan, aRange) {
  return aRange.low >= aPlan.low && aRange.high <= aPlan.high;
}

const low = room.daysTempRange.low;
const high = room.daysTempRange.high;
assert.equal(withinRange(plan, room.daysTempRange), withinRangeBefore(plan, low, high));
assert.equal(withinRange(plan, { low: 12, high: 20 }), false);
console.log(withinRange(plan, room.daysTempRange));
Output
true
Language What the example shows
JavaScript withinRange(plan, low, high) replaced with withinRange(plan, range), as above
Python the same change, with the range as a frozen dataclass
Go the same change; the range is a struct passed by value, so the function gets a copy and cannot change the range of the room
PythonGitHub
from dataclasses import dataclass


@dataclass(frozen=True)
class TempRange:
    low: int
    high: int


@dataclass(frozen=True)
class Plan:
    low: int
    high: int


def within_range_before(plan: Plan, bottom: int, top: int) -> bool:
    return bottom >= plan.low and top <= plan.high


def within_range(plan: Plan, temp_range: TempRange) -> bool:
    return temp_range.low >= plan.low and temp_range.high <= plan.high


days_temp_range = TempRange(18, 23)
plan = Plan(16, 24)
assert within_range(plan, days_temp_range) == within_range_before(plan, days_temp_range.low, days_temp_range.high)
assert not within_range(plan, TempRange(12, 20))
print(within_range(plan, days_temp_range))
Output
True
package main

import "fmt"

type TempRange struct{ Low, High int }

type Plan struct{ Low, High int }

func withinRangeBefore(p Plan, bottom, top int) bool {
	return bottom >= p.Low && top <= p.High
}

// withinRange gets a copy of the range, so it cannot change the range of the room.
func withinRange(p Plan, r TempRange) bool {
	return r.Low >= p.Low && r.High <= p.High
}

func main() {
	days := TempRange{Low: 18, High: 23}
	plan := Plan{Low: 16, High: 24}
	if withinRange(plan, days) != withinRangeBefore(plan, days.Low, days.High) || withinRange(plan, TempRange{12, 20}) {
		panic("mismatch")
	}
	fmt.Println(withinRange(plan, days))
}
Output
true

When to use

  • The same values come out of one object at each call. This is a sign of Data clumps and Long parameter list.
  • The function will need more of the object later. With the whole object, a new field needs no change to the signature.
  • The function only computes with the values of another object. This can be Feature envy. After the refactoring, see if the function belongs on the object it takes.

Pitfalls

A new dependency. The function now depends on the type of the whole object, not only on two numbers. If the function is in a module that must not know that type, keep the values, or define a small interface with only the fields that the function reads.

Callers without the object. Some callers have the two values but no object. They must then build one. If this is common, keep the old signature for them.

The values are not a part of one object. If the values come from different objects that are always used together, Preserve whole object does not apply. Make a new type with Introduce Parameter Object.

The function can get the value itself. If the function can compute a parameter from another parameter, remove it with Replace Parameter with Query.

Tools that do it

No IDE has one action for this refactoring. The steps use Extract Function, Change Function Declaration and Inline Function. See Change Function Declaration.

The catalogue lists the refactoring in the first edition, the second edition and the Ruby edition, with the tags refactoring-apis and parameters.2 In the second edition it is in Chapter 11, Refactoring APIs.3

References

  1. Martin Fowler, Catalog of Refactorings, Preserve Whole Object, the entry, the daysTempRange sketch
  2. Martin Fowler, Catalog of Refactorings, index, the entry preserveWholeObject, its books and tags
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 11, Refactoring APIs, Preserve Whole Object

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/72AAWM/text.yaml