Programming Search⌘K

Techniquecore

Parameterize function

Also called parameterize method.

Merge two or more functions that do the same work with different literal values into one function that takes the value as a parameter.

Family
refactoring
Intent
Turn the values that differ into a parameter.
Also called
Parameterize Method

Purpose

Two functions that differ only in a number or a string are one function written twice. A change to the shared logic must be made in each copy, and a third value needs a third copy.

Parameterize function replaces the copies with one function and makes the value that differed a parameter. The catalogue card merges tenPercentRaise and fivePercentRaise into raise(aPerson, factor).1 The first edition called the refactoring Parameterize Method, and the catalogue keeps that name as an alias.12

Steps

  1. Choose one of the similar functions as the start.
  2. Use Change Function Declaration to add a parameter for each literal that differs. See Change Function Declaration.
  3. In the body, replace the literal with the parameter. Test.
  4. Change each caller of that function to pass the literal it needs. Test.
  5. For each other similar function, replace its body with a call to the new function, then inline it into its callers. Test after each one.

If the functions differ in more than a value, for example in a range with a low and a high bound, the new function may need more than one parameter. If the logic differs, the functions are not copies, and this refactoring does not apply.

Example

Three functions charge a base rate for usage inside a band. They differ only in the bounds of the band. After the refactoring, withinBand(usage, bottom, top) replaces all three.

import assert from "node:assert/strict";

function bottomBand(usage) { return Math.min(usage, 100); }
function middleBand(usage) { return usage > 100 ? Math.min(usage, 200) - 100 : 0; }
function topBand(usage) { return usage > 200 ? usage - 200 : 0; }

function withinBand(usage, bottom, top) {
  return usage > bottom ? Math.min(usage, top) - bottom : 0;
}

for (const usage of [0, 50, 100, 150, 200, 350]) {
  assert.equal(withinBand(usage, 0, 100), bottomBand(usage));
  assert.equal(withinBand(usage, 100, 200), middleBand(usage));
  assert.equal(withinBand(usage, 200, Infinity), topBand(usage));
}

const charge = (usage) =>
  withinBand(usage, 0, 100) * 0.03 + withinBand(usage, 100, 200) * 0.05 + withinBand(usage, 200, Infinity) * 0.07;
assert.equal(charge(350).toFixed(2), "18.50");
console.log("parameterize function: tests pass");
Output
parameterize function: tests pass

The test checks that the new function gives the same result as each old function, at the bounds and between them, before the old functions are removed.

Language What the example shows
JavaScript three band functions merged into withinBand, as above
Python the same merge; math.inf is the top bound of the last band
Go the same merge with integer usage; math.MaxInt stands for no top bound
PythonGitHub
import math


def bottom_band(usage: float) -> float:
    return min(usage, 100)


def middle_band(usage: float) -> float:
    return min(usage, 200) - 100 if usage > 100 else 0


def top_band(usage: float) -> float:
    return usage - 200 if usage > 200 else 0


def within_band(usage: float, bottom: float, top: float) -> float:
    return min(usage, top) - bottom if usage > bottom else 0


for usage in [0, 50, 100, 150, 200, 350]:
    assert within_band(usage, 0, 100) == bottom_band(usage)
    assert within_band(usage, 100, 200) == middle_band(usage)
    assert within_band(usage, 200, math.inf) == top_band(usage)


def charge(usage: float) -> float:
    return (
        within_band(usage, 0, 100) * 0.03
        + within_band(usage, 100, 200) * 0.05
        + within_band(usage, 200, math.inf) * 0.07
    )


assert f"{charge(350):.2f}" == "18.50"
print("parameterize function: tests pass")
Output
parameterize function: tests pass
package main

import (
	"fmt"
	"math"
)

func bottomBand(usage int) int { return min(usage, 100) }

func middleBand(usage int) int {
	if usage > 100 {
		return min(usage, 200) - 100
	}
	return 0
}

func topBand(usage int) int {
	if usage > 200 {
		return usage - 200
	}
	return 0
}

// withinBand replaces the three functions above.
func withinBand(usage, bottom, top int) int {
	if usage > bottom {
		return min(usage, top) - bottom
	}
	return 0
}

func main() {
	for _, usage := range []int{0, 50, 100, 150, 200, 350} {
		if withinBand(usage, 0, 100) != bottomBand(usage) ||
			withinBand(usage, 100, 200) != middleBand(usage) ||
			withinBand(usage, 200, math.MaxInt) != topBand(usage) {
			panic(fmt.Sprint("mismatch at ", usage))
		}
	}
	fmt.Println("parameterize function: tests pass")
}
Output
parameterize function: tests pass

When to use

  • Duplicated code that differs in a value. See Duplicated Code.
  • A family of functions named after a value, such as tenPercentRaise and fivePercentRaise.1
  • Before a new case. When a new value is needed, a parameter is cheaper than a new copy.

Pitfalls

A flag is not a value. If the new parameter is a boolean that selects between two different behaviors, the result is a flag argument. That is the opposite move. See Remove Flag Argument.

Too many parameters. Each merge can add a parameter. When a function needs many of them, look at Long Parameter List.

Callers lose a name. tenPercentRaise(p) says what it does at the call. raise(p, 0.1) needs the reader to know what 0.1 means. A named constant at the call, or a thin wrapper for a common value, keeps the name.

Tools that do it

IDEs do the core step. In IntelliJ IDEA, "The Extract Parameter refactoring lets you extract a new parameter to a method."4 The tool replaces a literal in the body with a parameter and updates the callers. Merging the other copies is then a manual step.

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

References

  1. Martin Fowler, Catalog of Refactorings, Parameterize Function, the entry, the tenPercentRaise sketch; aliases Parameterize Method
  2. Martin Fowler, Catalog of Refactorings, index, the entry parameterizeFunction, its books and tags
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 11, Refactoring APIs, Parameterize Function
  4. JetBrains, IntelliJ IDEA documentation, Extract parameter, the first paragraph

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