Techniquecore
Change function declaration
Also called Rename Function, Rename Method, Add Parameter, Remove Parameter, Change Signature.
Change the name or the parameters of a function and update every caller, in one step when the callers are few and in stages when they are not.
- Family
- refactoring
- Intent
- Give a function the name and the parameters that say what it does and what it needs.
- Also called
- Rename Function, Rename Method, Add Parameter, Remove Parameter, Change Signature
Purpose
A function declaration is the joint where the rest of the program plugs in. The name tells a caller what the function does, and the parameters tell it what the function needs. When either is wrong, every call site carries the error. A function named circum makes each reader decode the name; a function that takes a whole customer when it needs only an address ties every caller to the customer type.
Change function declaration fixes the name, adds a parameter, removes one or changes what a parameter is, and updates each caller to match.1 The catalogue card shows the rename of circum(radius) to circumference(radius), and lists the aliases Rename Function, Rename Method, Add Parameter, Remove Parameter and Change Signature.2 The first edition had separate refactorings for the rename and for each kind of parameter change.3
The refactoring changes the interface and keeps the behaviour. A good name is often found only after the code is in use, so the refactoring is also how a team writes down what it has learned about a function.
Steps
The second edition gives two ways to make the change.1
In one step, when every caller can be found and changed at the same time:
- Run the tests and see them pass.
- If you remove a parameter, check that the body does not use it.
- Change the declaration to the one you want.
- Find each reference to the old declaration and update it.
- Test.
In stages (migration), when the callers are many, are hard to find, or are in code that you do not own:
- If needed, refactor the body so that the next step is clean.
- Use Extract Function on the body to make a function with the declaration you want. If the name must stay the same, give it a temporary name.
- If the change adds a parameter, decide what the old function passes for it.
- Test.
- Use Inline Function on the old function, one caller at a time, testing after each, until it has no callers. Then delete it.
- If the extracted function had a temporary name, rename it with the one-step way.
If the old function is part of a published interface, step 5 may never finish. Then mark the old function as deprecated and keep it as a call to the extracted one until its callers are gone.
Example
A function has a short name and takes a whole object when it needs one field. The migration keeps the old function as a thin wrapper while the callers move.
import assert from "node:assert/strict";
// Before: a cryptic name, and a parameter wider than the need.
function circum(circle) {
return 2 * Math.PI * circle.radius;
}
// Step 2: the body moves to a function with the declaration we want.
function circumference(radius) {
return 2 * Math.PI * radius;
}
// Step 3: the old function becomes a wrapper and passes the field.
/** @deprecated use circumference(radius) */
function circumOld(circle) {
return circumference(circle.radius);
}
const circles = [{ radius: 0 }, { radius: 1 }, { radius: 2.5 }];
for (const c of circles) {
assert.equal(circumOld(c), circum(c)); // the wrapper keeps the behaviour
assert.equal(circumference(c.radius), circum(c)); // a caller moved over
}
// Adding a parameter: a default value keeps the old calls valid.
function price(quantity, unitPrice, discount = 0) {
return quantity * unitPrice * (1 - discount);
}
assert.equal(price(3, 10), 30); // an old call, unchanged
assert.equal(price(3, 10, 0.5), 15); // a call that passes the discount
console.log("change function declaration: tests pass");
change function declaration: tests pass
Each step leaves the program working. A caller that still uses the old function gets the same result, and a caller that has moved uses the clearer declaration. The default value in price is the same idea for an added parameter: the old calls stay valid while the callers that need the parameter pass it.
| Language | What the example shows |
|---|---|
| JavaScript | a rename in stages and a parameter with a default, as above |
| Python | the same rename, and a keyword argument with a default |
| Go | the same rename; Go has no default values, so the old function supplies the value |
import math
import warnings
# Before: a cryptic name, and a parameter wider than the need.
def circum(circle):
return 2 * math.pi * circle["radius"]
# The body moves to a function with the declaration we want.
def circumference(radius):
return 2 * math.pi * radius
# The old function becomes a wrapper that warns and passes the field.
def circum_old(circle):
warnings.warn("use circumference(radius)", DeprecationWarning, stacklevel=2)
return circumference(circle["radius"])
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
for c in ({"radius": 0}, {"radius": 1}, {"radius": 2.5}):
assert circum_old(c) == circum(c)
assert circumference(c["radius"]) == circum(c)
assert len(caught) == 3 and caught[0].category is DeprecationWarning
# Adding a parameter: a keyword argument with a default keeps old calls valid.
def price(quantity, unit_price, *, discount=0.0):
return quantity * unit_price * (1 - discount)
assert price(3, 10) == 30
assert price(3, 10, discount=0.5) == 15
print("change function declaration: tests pass")
change function declaration: tests pass
package main
import (
"fmt"
"math"
)
type circle struct{ radius float64 }
// Before: a cryptic name, and a parameter wider than the need.
func circum(c circle) float64 {
return 2 * math.Pi * c.radius
}
// The body moves to a function with the declaration we want.
func circumference(radius float64) float64 {
return 2 * math.Pi * radius
}
// circumOld is the wrapper that callers use until they move.
//
// Deprecated: use circumference.
func circumOld(c circle) float64 {
return circumference(c.radius)
}
// Go has no default values. To add a parameter, the old function
// keeps its declaration and passes the value for its callers.
func priceWithDiscount(quantity int, unitPrice, discount float64) float64 {
return float64(quantity) * unitPrice * (1 - discount)
}
func price(quantity int, unitPrice float64) float64 {
return priceWithDiscount(quantity, unitPrice, 0)
}
func main() {
for _, c := range []circle{{0}, {1}, {2.5}} {
if circumOld(c) != circum(c) || circumference(c.radius) != circum(c) {
panic("behaviour changed")
}
}
if price(3, 10) != 30 || priceWithDiscount(3, 10, 0.5) != 15 {
panic("unexpected price")
}
fmt.Println("change function declaration: tests pass")
}
change function declaration: tests pass
When to use
- The name does not say what the function does. If you must read the body to know what a call means, the name is wrong.1
- The parameters tie the function to more than it needs. Passing one field, not the whole record, lets the function serve more callers. The opposite also holds: passing the record can be right when the function needs several of its fields. The choice depends on how the callers use the function.
- A parameter is not used. It makes each caller supply a value for nothing.
- Before other refactorings. A function that will move to another module or class often needs its parameters changed first.
- To treat a smell. The rename is the first fix for Mysterious Name.1
Pitfalls
Callers that the tools cannot see. A rename by a tool finds the calls that the tool can resolve. Calls by reflection, by a string name, from another repository or from a client of a published API are not found. Use the migration way for these.
Overloading and dispatch. In a language with overloading or with methods that override, a rename that changes one declaration and not the others can change which function a call reaches. Change the whole family of declarations together.
A removed argument with a side effect. If a caller passes an expression that does something, deleting the argument deletes the effect. gopls takes care of this: its remove-parameter fix preserves "the behavior of all existing calls" and does not delete an argument such as chargeCreditCard() that may have side effects.4
Defaults that hide a wrong call. A default value keeps the old calls valid, which is the point during a migration, and also hides a caller that should have passed a value. Remove the default when the migration is done if every caller should choose.
Tools that do it
| Tool | Languages | What it automates |
|---|---|---|
| IntelliJ IDEA | Java, Kotlin | Change Signature can "change the method name, add, remove, reorder, and rename parameters and exceptions", and it offers a default value for an added parameter.5 |
| gopls | Go | removes an unused parameter "using a ChangeSignature command, updating all callers", and moves a parameter left or right, "updating all callers accordingly"4 |
| VS Code | TypeScript, JavaScript | Rename (F2) "across your TypeScript project", and "Convert parameters to destructured object"6 |
A tool does the one-step way. The migration way, with a wrapper and a deprecation, is a sequence of tool steps (extract, then inline at each caller) that the programmer plans.
References
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 6, A First Set of Refactorings, Change Function Declaration, motivation and mechanics; Chapter 3, Bad Smells in Code, Mysterious Name
- Martin Fowler, Catalog of Refactorings, Change Function Declaration, the entry; aliases Rename Function, Rename Method, Add Parameter, Remove Parameter, Change Signature
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 10, Making Method Calls Simpler, Rename Method, Add Parameter and Remove Parameter
- gopls documentation, Code transformation features, Remove unused parameter, and Move function parameters
- IntelliJ IDEA documentation, Change signature, the introduction and the section on default values
- Visual Studio Code documentation, Refactoring TypeScript and JavaScript, Rename, and Convert parameters to destructured 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag NRRZP1 Edit this page History Report an error Markdown