Techniquecore
Combine functions into transform
Also called enrich function.
Gather the calculations of values derived from a record into one function that takes the record and returns a copy with the derived values added.
- Family
- refactoring
- Intent
- Compute the values derived from a record in one place, and give them to every reader as fields of an enriched copy.
Purpose
Programs often read a record and then compute values from it: a charge from a reading, a total from an order, a chargeable weight from a parcel. When several parts of the program need the same derived value, each tends to compute it for itself, and the rule is repeated. When the rule changes, one copy is missed.
Combine functions into transform puts all these calculations in one function. The function takes the source record, makes a copy, adds each derived value as a field of the copy, and returns it. Every reader then takes the derived values from the enriched record. The catalogue card shows base(aReading) and taxableCharge(aReading) combined into enrichReading(argReading), which deep-clones the reading and sets baseCharge and taxableCharge on the clone.1
The refactoring is the twin of Combine Functions into Class. Both give the derived logic one home. The book gives the rule for the choice: if the code updates the source data, use a class, because a transform stores the derived values when it runs and they do not follow later changes.2 A transform fits data that is read, enriched and passed on, as in a pipeline.
Steps
- Run the tests and see them pass.
- Write a transform function that takes the record and returns a deep copy of it, with no other change. Add a test that the source record is not changed.
- Pick one derived value. Move its calculation into the transform, as a field of the copy.
- Change one reader to take the field, and test. Change the other readers in the same way, testing after each.
- Repeat for each derived value.
- Name the transform after what it does. The book uses the name
enrich...when the output is the same record with more fields, andtransform...when the output is a different thing.2
Example
Two parts of a shipping program compute the chargeable weight of a parcel. After the refactoring, one function enriches the parcel and both parts read the field.
import assert from "node:assert/strict";
const DIVISOR = 5000; // cm^3 per kg of volumetric weight
// Before: two readers repeat the derived rule.
function label(p) {
const w = Math.max(p.weightKg, (p.length * p.width * p.height) / DIVISOR);
return `${p.id}: ${Math.ceil(w)} kg`;
}
function cost(p, rate) {
const w = Math.max(p.weightKg, (p.length * p.width * p.height) / DIVISOR);
return Math.ceil(w) * rate;
}
// After: one transform computes the derived values on a copy.
function enrichParcel(source) {
const p = structuredClone(source);
p.volume = p.length * p.width * p.height;
p.chargeableKg = Math.ceil(Math.max(p.weightKg, p.volume / DIVISOR));
return p;
}
const labelAfter = (p) => `${p.id}: ${p.chargeableKg} kg`;
const costAfter = (p, rate) => p.chargeableKg * rate;
const raw = { id: "P1", length: 40, width: 30, height: 20, weightKg: 2, tags: ["fragile"] };
const parcel = enrichParcel(raw);
assert.equal(labelAfter(parcel), label(raw));
assert.equal(costAfter(parcel, 3), cost(raw, 3));
assert.equal("chargeableKg" in raw, false); // the source is not changed
parcel.tags.push("express");
assert.deepEqual(raw.tags, ["fragile"]); // a deep copy: nested data is not shared
// The trap: a change to the source after the transform is not seen.
raw.weightKg = 30;
assert.equal(labelAfter(parcel), "P1: 5 kg"); // stale
assert.equal(labelAfter(enrichParcel(raw)), "P1: 30 kg");
console.log("combine functions into transform: tests pass");
combine functions into transform: tests pass
structuredClone makes a deep copy, so the enriched record shares no nested object with the source.3 The last lines show why the book prefers a class when the source changes: the enriched copy keeps the weight it was made with.
| Language | What the example shows |
|---|---|
| JavaScript | an enrich function with structuredClone, and a stale copy, as above |
| Python | the same transform with copy.deepcopy, and the difference from a shallow copy |
| Go | a transform that returns a struct with the source and the derived fields |
import copy
import math
DIVISOR = 5000 # cm^3 per kg of volumetric weight
def enrich_parcel(source):
p = copy.deepcopy(source)
p["volume"] = p["length"] * p["width"] * p["height"]
p["chargeable_kg"] = math.ceil(max(p["weight_kg"], p["volume"] / DIVISOR))
return p
raw = {"id": "P1", "length": 40, "width": 30, "height": 20, "weight_kg": 2, "tags": ["fragile"]}
parcel = enrich_parcel(raw)
assert parcel["chargeable_kg"] == 5 and "chargeable_kg" not in raw
parcel["tags"].append("express")
assert raw["tags"] == ["fragile"] # deep copy: the list is not shared
# With a shallow copy, the nested list is shared with the source.
shallow = copy.copy(raw)
shallow["tags"].append("express")
print("source tags after a change to the shallow copy:", raw["tags"])
assert raw["tags"] == ["fragile", "express"]
print("combine functions into transform: tests pass")
source tags after a change to the shallow copy: ['fragile', 'express']
combine functions into transform: tests pass
package main
import (
"fmt"
"math"
"slices"
)
const divisor = 5000.0 // cm^3 per kg of volumetric weight
type Parcel struct {
ID string
Length, Width, Height float64
WeightKg float64
Tags []string
}
// The output type says that the derived fields are there.
type EnrichedParcel struct {
Parcel
Volume float64
ChargeableKg float64
}
func enrichParcel(p Parcel) EnrichedParcel {
p.Tags = slices.Clone(p.Tags) // a struct copy shares the slice; clone it
v := p.Length * p.Width * p.Height
return EnrichedParcel{Parcel: p, Volume: v, ChargeableKg: math.Ceil(math.Max(p.WeightKg, v/divisor))}
}
func main() {
raw := Parcel{ID: "P1", Length: 40, Width: 30, Height: 20, WeightKg: 2, Tags: []string{"fragile"}}
e := enrichParcel(raw)
e.Tags[0] = "express"
fmt.Println(e.ID, e.ChargeableKg, raw.Tags)
if e.ChargeableKg != 5 || raw.Tags[0] != "fragile" {
panic("unexpected result")
}
fmt.Println("combine functions into transform: tests pass")
}
P1 5 [fragile]
combine functions into transform: tests pass
When to use
- Several readers compute the same derived value. The repeated rule is Duplicated Code, and the transform is one home for it.
- The data is read, not updated. Records read from a file, a request or a database, enriched once and passed on.
- The program is a pipeline. A transform is one stage, and it can be followed by others. Combined with Split Phase, it often becomes the first phase that prepares the data.
Pitfalls
Stale derived values. The fields are computed when the transform runs. If code changes the source afterwards, the fields are wrong. The example shows this. If the data changes, use a class.2
A shallow copy. A shallow copy shares the nested objects with the source, so adding to a nested list in the copy also changes the source. The Python documentation puts the difference so: a shallow copy "inserts references into it to the objects found in the original", while a deep copy "inserts copies into it of the objects found in the original".4
Readers that still compute. A reader that keeps its own copy of the rule defeats the refactoring. Search for the calculation after the change, and remove the copies.
Many transforms on one record. Two transforms that both add fields to the same record can disagree, or overwrite each other. Keep one transform for one kind of derived data.
Tools that do it
This refactoring is a sequence of steps, not one action of a tool: an Extract Function for each calculation, a move of the calculation into the transform, and a change of each reader. The extraction and the rename steps can use the actions of the tools, and the tests check each step.
References
- Martin Fowler, Catalog of Refactorings, Combine Functions into Transform, the entry
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 6, A First Set of Refactorings, Combine Functions into Transform, motivation and mechanics
- MDN Web Docs, Window, structuredClone() method, the introduction
- Python documentation, copy, Shallow and deep copy operations, the difference between shallow and deep copying
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag EKTA28 Edit this page History Report an error Markdown