Skip to content

Move Function: Put Behaviour Next to the Data It Uses

Learn how to move a function to the class or module whose data it reads most, in small test-backed steps, with TypeScript, Python and PHP examples.

6 min readRefactoring

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)); // 4140

After

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)); // 4140

Why 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.
  • InvoiceBuilder shrinks to its real job: tax and line totals.
  • Other features can get overtime from a booking without building an invoice object.
  • Booking gains 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.

  1. Make sure tests cover lineTotalCents and every other caller of overtimeCents, including a booking that ends early and one that runs exactly to the included minutes.

  2. Read the function body and list what it uses. Confirm it reads only Booking fields and nothing from this, so it can move without dragging other state along.

  3. Copy the function into Booking as overtimeCents() with no parameter, replacing each booking. with this. (or self.). Leave the original in place. Run the tests.

  4. Add a unit test that calls booking.overtimeCents() directly, using the same cases as the existing tests. Run the tests.

  5. Change the body of InvoiceBuilder.overtimeCents(booking) to return booking.overtimeCents() so the old method only delegates. Run the tests.

  6. Update callers one at a time, starting with lineTotalCents, to call booking.overtimeCents() directly. Run the tests after each caller.

  7. 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.

Next guide2 of 5 · Techniques: moving featuresExtract Class: Split a Class That Does Two JobsRead the next one