Techniquecore
Return modified value
Change a function that updates a variable outside itself so that it computes the value and returns it, and let the caller assign the result.
- Family
- refactoring
- Intent
- Make the data that a function changes visible at the call.
Purpose
When a function changes a variable that the caller owns, the call does not show the change. A reader who sees calculateAscent(); cannot tell that the call writes to totalAscent. To find out which code changes the variable, the reader must read the body of each function.
Return modified value makes the function compute the value and return it. The caller assigns the result. The catalogue card starts with let totalAscent = 0; calculateAscent();, where the function adds to the outer variable totalAscent. After the refactoring, the call is const totalAscent = calculateAscent();, and the function sums into a local result that it returns.1
The variable can now be a const, and the data flow is in the call.
Steps
- Make the function return the value of the variable that it changes. Assign the result to the variable at the call.
- Test.
- Declare a local variable in the function for the value, and use it in place of the outer variable.
- Test. If the outer variable is no longer changed anywhere else, make it a constant.
- Rename the local variable, for example to
result.
The refactoring works best when the function changes one value. For two or more values, split the function first, for example with Split Variable and Extract Function.
Example
A route is a list of points with an elevation. The total ascent is the sum of each climb between two points.
import assert from "node:assert/strict";
const points = [{ elevation: 10 }, { elevation: 25 }, { elevation: 20 }, { elevation: 32 }];
let totalAscentBefore = 0;
function calculateAscentBefore() {
for (let i = 1; i < points.length; i++) {
const verticalChange = points[i].elevation - points[i - 1].elevation;
totalAscentBefore += verticalChange > 0 ? verticalChange : 0;
}
}
calculateAscentBefore();
function calculateAscent(points) {
let result = 0;
for (let i = 1; i < points.length; i++) {
const verticalChange = points[i].elevation - points[i - 1].elevation;
result += verticalChange > 0 ? verticalChange : 0;
}
return result;
}
const totalAscent = calculateAscent(points);
assert.equal(totalAscent, totalAscentBefore);
// A second call of the old function changes the total again.
calculateAscentBefore();
assert.equal(totalAscentBefore, 2 * totalAscent);
// A second call of the new function changes nothing.
assert.equal(calculateAscent(points), totalAscent);
console.log(totalAscent);
27
The new function also takes the points as a parameter. That step is Replace Query with Parameter, and it is not a part of this refactoring.
| Language | What the example shows |
|---|---|
| JavaScript | calculateAscent changed from an update of an outer let to a function that returns the total, as above |
| Python | the same change; the old version must declare the outer name with global to assign to it |
| Go | the same change; the old version updates a variable through a pointer argument |
points = [10, 25, 20, 32]
total_ascent_before = 0
def calculate_ascent_before() -> None:
global total_ascent_before
for previous, current in zip(points, points[1:]):
total_ascent_before += max(current - previous, 0)
calculate_ascent_before()
def calculate_ascent(elevations: list[int]) -> int:
return sum(max(current - previous, 0) for previous, current in zip(elevations, elevations[1:]))
TOTAL_ASCENT = calculate_ascent(points)
assert TOTAL_ASCENT == total_ascent_before
calculate_ascent_before()
assert total_ascent_before == 2 * TOTAL_ASCENT
assert calculate_ascent(points) == TOTAL_ASCENT
print(TOTAL_ASCENT)
27
package main
import "fmt"
// calculateAscentBefore adds to a total that the caller owns.
func calculateAscentBefore(elevations []int, total *int) {
for i := 1; i < len(elevations); i++ {
if change := elevations[i] - elevations[i-1]; change > 0 {
*total += change
}
}
}
func calculateAscent(elevations []int) int {
result := 0
for i := 1; i < len(elevations); i++ {
if change := elevations[i] - elevations[i-1]; change > 0 {
result += change
}
}
return result
}
func main() {
points := []int{10, 25, 20, 32}
before := 0
calculateAscentBefore(points, &before)
totalAscent := calculateAscent(points)
if totalAscent != before {
panic("mismatch")
}
calculateAscentBefore(points, &before)
if before != 2*totalAscent || calculateAscent(points) != totalAscent {
panic("mismatch")
}
fmt.Println(totalAscent)
}
27
When to use
- A function writes to a variable of the caller or to a global. See Global data and Mutable data.
- One value is changed. The refactoring then turns the function into one that returns that value. If the function has no other side effect, it becomes a query. See Separate Query from Modifier.
- Before you move the function. A function that returns its result can move to another module, and the caller keeps the variable.
Pitfalls
Many values. A function that updates two or three variables cannot return all of them as one plain value. Return a record or a tuple only if the values belong together. Otherwise, split the function.
Large data. A function that changes a large array in place can be faster than one that returns a new copy. This refactoring is for values. For a large structure, keep the in-place change, and make it clear in the name of the function.
Other writers. If other code also writes to the same variable, the variable cannot become a constant. Then the refactoring only makes one of the writes visible.
Tools that do it
No IDE has one action for this refactoring. The changes are small, and the steps are done by hand.
The catalogue lists the refactoring in the second edition only, with the tags refactoring-apis and immutability.2 In the second edition it is in Chapter 11, Refactoring APIs.3
References
- Martin Fowler, Catalog of Refactorings, Return Modified Value, the entry, the totalAscent and calculateAscent sketch
- Martin Fowler, Catalog of Refactorings, index, the entry returnModifiedValue, its books and tags
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 11, Refactoring APIs, Return Modified Value
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 ZZV861 Edit this page History Report an error Markdown