Move Function relocates a function from the module where it happens to live to the module whose data it actually works with. The body barely changes. What changes is its address, and with it who owns the logic. Interviewers often show you a method that keeps reaching into another object and ask what is wrong with it. If you can name the smell, move the function safely in front of them and explain what got better, you show that you think about where code belongs as well as whether it works.
The problem
A situation where the obvious design starts to hurt.
DeskHop is a coworking booking service. Its InvoiceBuilder has a method overtimeCents that works out how much to charge when a member keeps a desk past the minutes included in their booking. The method reads five fields of Booking and nothing from InvoiceBuilder itself.
The result is that the overtime rule lives far from the data it depends on. When the product team changed overtime billing from hourly to 30-minute blocks, someone had to remember that the rule sat in the invoicing code and not with bookings. The receipt emailer and the admin dashboard both needed the same number, so each one had to import an invoice builder only to ask it a question about a booking. Booking itself is a bag of fields with no behaviour.
Before and after
The same code, before and after the change.
Before
class Booking {
constructor(
public readonly deskId: string,
public readonly startMinute: number,
public readonly endMinute: number,
public readonly includedMinutes: number,
public readonly overtimeCentsPerHalfHour: number,
) {}
}
class InvoiceBuilder {
constructor(private readonly vatPercent: number) {}
overtimeCents(booking: Booking): number {
const used = booking.endMinute - booking.startMinute;
const extra = used - booking.includedMinutes;
if (extra <= 0) return 0;
const blocks = Math.ceil(extra / 30);
return blocks * booking.overtimeCentsPerHalfHour;
}
lineTotalCents(booking: Booking, baseCents: number): number {
const net = baseCents + this.overtimeCents(booking);
return Math.floor((net * (100 + this.vatPercent) + 50) / 100);
}
}
const invoice = new InvoiceBuilder(20);
const booking = new Booking("D-14", 540, 1105, 480, 350);
console.log(invoice.lineTotalCents(booking, 2400)); // 4140import math
from dataclasses import dataclass
@dataclass(frozen=True)
class Booking:
desk_id: str
start_minute: int
end_minute: int
included_minutes: int
overtime_cents_per_half_hour: int
class InvoiceBuilder:
def __init__(self, vat_percent: int) -> None:
self.vat_percent = vat_percent
def overtime_cents(self, booking: Booking) -> int:
used = booking.end_minute - booking.start_minute
extra = used - booking.included_minutes
if extra <= 0:
return 0
blocks = math.ceil(extra / 30)
return blocks * booking.overtime_cents_per_half_hour
def line_total_cents(self, booking: Booking, base_cents: int) -> int:
net = base_cents + self.overtime_cents(booking)
return (net * (100 + self.vat_percent) + 50) // 100
invoice = InvoiceBuilder(20)
booking = Booking("D-14", 540, 1105, 480, 350)
print(invoice.line_total_cents(booking, 2400)) # 4140<?php
final class Booking
{
public function __construct(
public readonly string $deskId,
public readonly int $startMinute,
public readonly int $endMinute,
public readonly int $includedMinutes,
public readonly int $overtimeCentsPerHalfHour,
) {}
}
final class InvoiceBuilder
{
public function __construct(private readonly int $vatPercent) {}
public function overtimeCents(Booking $booking): int
{
$used = $booking->endMinute - $booking->startMinute;
$extra = $used - $booking->includedMinutes;
if ($extra <= 0) {
return 0;
}
$blocks = (int) ceil($extra / 30);
return $blocks * $booking->overtimeCentsPerHalfHour;
}
public function lineTotalCents(Booking $booking, int $baseCents): int
{
$net = $baseCents + $this->overtimeCents($booking);
return intdiv($net * (100 + $this->vatPercent) + 50, 100);
}
}
$invoice = new InvoiceBuilder(20);
$booking = new Booking('D-14', 540, 1105, 480, 350);
echo $invoice->lineTotalCents($booking, 2400), PHP_EOL; // 4140After
class Booking {
constructor(
public readonly deskId: string,
public readonly startMinute: number,
public readonly endMinute: number,
public readonly includedMinutes: number,
public readonly overtimeCentsPerHalfHour: number,
) {}
overtimeCents(): number {
const used = this.endMinute - this.startMinute;
const extra = used - this.includedMinutes;
if (extra <= 0) return 0;
const blocks = Math.ceil(extra / 30);
return blocks * this.overtimeCentsPerHalfHour;
}
}
class InvoiceBuilder {
constructor(private readonly vatPercent: number) {}
lineTotalCents(booking: Booking, baseCents: number): number {
const net = baseCents + booking.overtimeCents();
return Math.floor((net * (100 + this.vatPercent) + 50) / 100);
}
}
const invoice = new InvoiceBuilder(20);
const booking = new Booking("D-14", 540, 1105, 480, 350);
console.log(invoice.lineTotalCents(booking, 2400)); // 4140import math
from dataclasses import dataclass
@dataclass(frozen=True)
class Booking:
desk_id: str
start_minute: int
end_minute: int
included_minutes: int
overtime_cents_per_half_hour: int
def overtime_cents(self) -> int:
used = self.end_minute - self.start_minute
extra = used - self.included_minutes
if extra <= 0:
return 0
blocks = math.ceil(extra / 30)
return blocks * self.overtime_cents_per_half_hour
class InvoiceBuilder:
def __init__(self, vat_percent: int) -> None:
self.vat_percent = vat_percent
def line_total_cents(self, booking: Booking, base_cents: int) -> int:
net = base_cents + booking.overtime_cents()
return (net * (100 + self.vat_percent) + 50) // 100
invoice = InvoiceBuilder(20)
booking = Booking("D-14", 540, 1105, 480, 350)
print(invoice.line_total_cents(booking, 2400)) # 4140<?php
final class Booking
{
public function __construct(
public readonly string $deskId,
public readonly int $startMinute,
public readonly int $endMinute,
public readonly int $includedMinutes,
public readonly int $overtimeCentsPerHalfHour,
) {}
public function overtimeCents(): int
{
$used = $this->endMinute - $this->startMinute;
$extra = $used - $this->includedMinutes;
if ($extra <= 0) {
return 0;
}
$blocks = (int) ceil($extra / 30);
return $blocks * $this->overtimeCentsPerHalfHour;
}
}
final class InvoiceBuilder
{
public function __construct(private readonly int $vatPercent) {}
public function lineTotalCents(Booking $booking, int $baseCents): int
{
$net = $baseCents + $booking->overtimeCents();
return intdiv($net * (100 + $this->vatPercent) + 50, 100);
}
}
$invoice = new InvoiceBuilder(20);
$booking = new Booking('D-14', 540, 1105, 480, 350);
echo $invoice->lineTotalCents($booking, 2400), PHP_EOL; // 4140Why it's worth it
What the change buys you.
A quick test for where a function belongs is to count what it touches. overtimeCents read five things from Booking and nothing from InvoiceBuilder. That is feature envy: the method is more interested in another object than in its own. Once it moves, the overtime rule sits next to the fields it depends on. A change to how bookings are measured and a change to how they are charged now happen in the same file.
The invoice builder gets narrower too. It now knows about tax and line totals, and it asks the booking for one number instead of picking through its fields. Any other code that needs overtime, such as the receipt emailer or the dashboard, calls booking.overtimeCents() directly and no longer needs an invoice builder it has no other use for.
Behaviour is unchanged. The arithmetic is identical and the example still prints 4140: 565 minutes used, 85 over the included 480, rounded up to three half-hour blocks at 350 cents, plus a 2400 base and 20 percent VAT.
- The overtime rule sits next to the booking fields it depends on, so a billing change touches one class.
InvoiceBuildershrinks to its real job: tax and line totals.- Other features can get overtime from a booking without building an invoice object.
Bookinggains real behaviour and stops being a passive record that other classes pick apart.
Careful with
- If the function reads data from both modules in similar amounts, moving it can just shift the envy the other way. Pass the few values it needs from the old side as parameters, or split it first with Extract Function.
- If the old method is part of a public API or used by other services, keep the delegating version and mark it deprecated instead of deleting it right away.
- Watch for subclasses that override the old method. Moving it can silently skip the override, so check the inheritance tree before you delete anything.
- Do not move a function onto a value that crosses a serialisation boundary unless the receiving side also has the class. Plain JSON objects will not carry the new method.
Step by step
Small, safe steps, with the tests passing after each.
Make sure tests cover
lineTotalCentsand every other caller ofovertimeCents, including a booking that ends early and one that runs exactly to the included minutes.Read the function body and list what it uses. Confirm it reads only
Bookingfields and nothing fromthis, so it can move without dragging other state along.Copy the function into
BookingasovertimeCents()with no parameter, replacing eachbooking.withthis.(orself.). Leave the original in place. Run the tests.Add a unit test that calls
booking.overtimeCents()directly, using the same cases as the existing tests. Run the tests.Change the body of
InvoiceBuilder.overtimeCents(booking)toreturn booking.overtimeCents()so the old method only delegates. Run the tests.Update callers one at a time, starting with
lineTotalCents, to callbooking.overtimeCents()directly. Run the tests after each caller.When a search finds no remaining callers of the delegating method, delete it from
InvoiceBuilder. Run the tests.
Smells it removes
Smells this refactoring helps remove.
Common questions
Short answers to the usual doubts.
How do I decide which module a function belongs in?
Count what it touches. If most of the fields it reads and the methods it calls belong to one module, move it there. Also look at what changes together: if every edit to the function follows a change to Booking, it belongs with Booking. When the counts are close, leave it where it is or split it first.
Is Move Function the same as Move Method?
It is the same idea. Move Method is the name from class-based code. Move Function also covers free functions moved between modules or files, and functions nested inside other functions. The mechanics are the same: copy, delegate, redirect callers, delete.
Why keep a delegating method instead of moving everything in one go?
Delegation lets you change one caller at a time and run the tests between each change. If something breaks, you know which caller did it. In a small codebase you can redirect everything at once, but the delegating step is what keeps the refactoring safe when callers are spread across many files or teams.