Techniquecore
Move function
Also called move method.
Move a function to the class or module whose data it uses most, and leave a delegating call or nothing behind; called Move Method in the first edition of Refactoring.
- Family
- refactoring
- Intent
- Put a function next to the data and the other functions it works with.
- Also called
- Move Method
Purpose
Good modules keep things that change together in one place. A function that uses the data of another class more than the data of its own is in the wrong place: each change to that data sends you to two places, and each reader must hold both in mind.
Move function puts the function in the class or module where its data lives. The catalogue card moves an overdraftCharge getter from an account to its account type.1 The first edition calls the refactoring Move Method; the catalogue keeps that name as an alias.12 The second edition calls it Move Function, and its first worked example moves a nested function, not a method, to the top level of its module.3
It is the main fix the book gives for Feature Envy.3
Steps
- Look at everything the function uses in its current place: fields, other functions, parameters. Decide whether some of them should move with it.3
- Check whether the function is polymorphic: an override in a subclass or an implementation of an interface makes the move harder.
- Copy the function to the target. Change it to fit: data that was on
thiscomes in through a parameter or is now the target's own. - Decide how the source will reach the target, and turn the source function into a call that delegates to the copy.3
- Test.
- If the delegating function adds nothing, inline it into its callers with Inline Function, and test.
Example
The cost to ship an order uses only the parcel's weight and size. It moves to the parcel. The order keeps a delegating getter for a time; then the callers ask the parcel.
import assert from "node:assert/strict";
class Parcel {
constructor(weightKg, cm) { this.weightKg = weightKg; this.cm = cm; }
// Moved here: it uses only the parcel's data.
get shippingCents() {
const volumetricKg = (this.cm[0] * this.cm[1] * this.cm[2]) / 5000;
return 400 + Math.ceil(Math.max(this.weightKg, volumetricKg)) * 150;
}
}
class Order {
constructor(id, parcel) { this.id = id; this.parcel = parcel; }
// Step 4: the old function delegates while callers change.
get shippingCents() { return this.parcel.shippingCents; }
}
const light = new Order(1, new Parcel(0.8, [10, 10, 5]));
const bulky = new Order(2, new Parcel(1.2, [60, 40, 40]));
assert.equal(light.shippingCents, 550); // 1 kg billed
assert.equal(bulky.shippingCents, 3400); // 19.2 kg by volume, 20 billed
assert.equal(bulky.parcel.shippingCents, bulky.shippingCents);
console.log("move function: tests pass");
move function: tests pass
The parcel rule can now change without a change to the order, and a return label, which has a parcel but no order, can use it.
| Language | What the example shows |
|---|---|
| JavaScript | a getter moved to the class whose data it uses, with a delegating getter left for a time |
| Python | the same move, with a property |
| Java | the same move between two classes, as the IntelliJ Move action does for a method |
| Go | the same move from a method on one type to a method on another |
import math
from dataclasses import dataclass
@dataclass(frozen=True)
class Parcel:
weight_kg: float
cm: tuple[int, int, int]
@property
def shipping_cents(self) -> int:
# Moved here from Order: it uses only the parcel's data.
volumetric_kg = self.cm[0] * self.cm[1] * self.cm[2] / 5000
return 400 + math.ceil(max(self.weight_kg, volumetric_kg)) * 150
@dataclass(frozen=True)
class Order:
order_id: int
parcel: Parcel
@property
def shipping_cents(self) -> int:
return self.parcel.shipping_cents # delegates while callers change
assert Order(1, Parcel(0.8, (10, 10, 5))).shipping_cents == 550
assert Order(2, Parcel(1.2, (60, 40, 40))).shipping_cents == 3400
print("move function: tests pass")
move function: tests pass
public class Main {
record Parcel(double weightKg, int l, int w, int h) {
// Moved here from Order: it uses only the parcel's data.
long shippingCents() {
double volumetricKg = (double) l * w * h / 5000;
return 400 + (long) Math.ceil(Math.max(weightKg, volumetricKg)) * 150;
}
}
record Order(int id, Parcel parcel) {
long shippingCents() { return parcel.shippingCents(); } // delegates for a time
}
public static void main(String[] args) {
if (new Order(1, new Parcel(0.8, 10, 10, 5)).shippingCents() != 550) throw new AssertionError("light");
if (new Order(2, new Parcel(1.2, 60, 40, 40)).shippingCents() != 3400) throw new AssertionError("bulky");
System.out.println("move function: tests pass");
}
}
move function: tests pass
package main
import (
"fmt"
"math"
)
type Parcel struct {
WeightKg float64
CM [3]float64
}
// ShippingCents moved here from Order: it uses only the parcel's data.
func (p Parcel) ShippingCents() int {
volumetricKg := p.CM[0] * p.CM[1] * p.CM[2] / 5000
return 400 + int(math.Ceil(math.Max(p.WeightKg, volumetricKg)))*150
}
type Order struct {
ID int
Parcel Parcel
}
// ShippingCents delegates while the callers change.
func (o Order) ShippingCents() int { return o.Parcel.ShippingCents() }
func main() {
light := Order{1, Parcel{0.8, [3]float64{10, 10, 5}}}
bulky := Order{2, Parcel{1.2, [3]float64{60, 40, 40}}}
if light.ShippingCents() != 550 || bulky.ShippingCents() != 3400 {
panic(fmt.Sprint(light.ShippingCents(), bulky.ShippingCents()))
}
fmt.Println("move function: tests pass")
}
move function: tests pass
When to use
- The function uses another class's data more than its own. That is Feature Envy.3
- One change touches several classes. Moving functions together is one fix for Shotgun Surgery.
- A helper is nested where others need it. A function nested in another can move out to module level when a second caller needs it.3
- After other refactorings. Once you know the shape of the data, functions move to where it is. See Combine Functions into Class.
Pitfalls
Data that does not move. If the function also uses some of the source's data, pass it in as a parameter, or move that data too with Move Field. Passing the whole source object brings back the coupling.
Polymorphism. A method that subclasses override cannot move as one function. Move each override, or keep a polymorphic call that delegates.
Unclear target. If the function uses the data of several classes, the book's rule is to put it with the class that has most of the data, and to use Extract Function first to split it into parts that can go to different places.3
Tools that do it
IntelliJ IDEA's Move action lets you move "class members to other classes", and its documentation gives the case of a method "used more in another class than in its own class".4 In other languages, and for module-level functions, the steps above are done by hand or with the move action of the tool.
References
- Martin Fowler, Catalog of Refactorings, Move Function, the entry; aliases Move Method
- Martin Fowler, Refactoring, Improving the Design of Existing Code, Addison-Wesley, 1999, Chapter 7, Moving Features Between Objects, Move Method
- Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 8, Moving Features, Move Function, motivation and mechanics; Chapter 3, Bad Smells in Code, Feature Envy
- IntelliJ IDEA documentation, Move refactorings, the introduction; Move static method to another class; Move an instance method to another class
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 ET0CNN Edit this page History Report an error Markdown