Replace Function with Command takes a function and gives it its own class. The parameters become fields, the body moves into an execute method, and each step of the old body becomes a small method that reads those fields directly. Callers can keep using the original function, which now just builds the object and runs it.
This guide walks through the refactoring on a monthly invoice calculator for an invented coworking company called Deskhive. You will see the code before and after in TypeScript, Python and PHP, the safe steps that get you there, and when the extra class is worth having. Interviewers often bring this refactoring up when they ask how you would break up a long function whose local variables are tangled together.
The problem
A situation where the obvious design starts to hurt.
Deskhive bills members once a month. A single function, monthlyInvoiceCents, works out the plan fee with an annual discount, charges for meeting-room hours beyond the plan allowance (with a cheaper rate after 20 extra hours), charges for guest passes (offices get one free), and adds VAT. Every block is introduced by a comment, and each block needs the member, the usage and sometimes the results of earlier blocks.
You could try Extract Function, but each extracted helper would need member, usage and the plan passed in again. The parameter lists would grow, and the helpers would end up loose at module level, detached from the calculation they belong to. The function is long because its steps share context, and a plain function has nowhere to keep that context except local variables.
Before and after
The same code, before and after the change.
Before
type Plan = "hot-desk" | "fixed-desk" | "office";
interface Member {
plan: Plan;
annual: boolean;
}
interface Usage {
roomHours: number;
guestPasses: number;
}
const PLAN_CENTS: Record<Plan, number> = { "hot-desk": 19000, "fixed-desk": 29000, office: 65000 };
const INCLUDED_ROOM_HOURS: Record<Plan, number> = { "hot-desk": 2, "fixed-desk": 5, office: 10 };
export function monthlyInvoiceCents(member: Member, usage: Usage, vatPercent: number): number {
// plan fee, 10% off for annual commitment
let base = PLAN_CENTS[member.plan];
if (member.annual) {
base = Math.floor((base * 9) / 10);
}
// meeting rooms beyond the allowance, cheaper after 20 extra hours
const extraHours = Math.max(0, usage.roomHours - INCLUDED_ROOM_HOURS[member.plan]);
let roomCharge = extraHours * 1500;
if (extraHours > 20) {
roomCharge = 20 * 1500 + (extraHours - 20) * 1200;
}
// guest passes, first one free for offices
const billableGuests = member.plan === "office" ? Math.max(0, usage.guestPasses - 1) : usage.guestPasses;
const guestCharge = billableGuests * 800;
// VAT, rounded half up to the cent
const net = base + roomCharge + guestCharge;
const vat = Math.floor((net * vatPercent + 50) / 100);
return net + vat;
}
console.log(monthlyInvoiceCents({ plan: "office", annual: true }, { roomHours: 34, guestPasses: 3 }, 20));from dataclasses import dataclass
PLAN_CENTS = {"hot-desk": 19000, "fixed-desk": 29000, "office": 65000}
INCLUDED_ROOM_HOURS = {"hot-desk": 2, "fixed-desk": 5, "office": 10}
@dataclass(frozen=True)
class Member:
plan: str
annual: bool
@dataclass(frozen=True)
class Usage:
room_hours: int
guest_passes: int
def monthly_invoice_cents(member: Member, usage: Usage, vat_percent: int) -> int:
# plan fee, 10% off for annual commitment
base = PLAN_CENTS[member.plan]
if member.annual:
base = base * 9 // 10
# meeting rooms beyond the allowance, cheaper after 20 extra hours
extra_hours = max(0, usage.room_hours - INCLUDED_ROOM_HOURS[member.plan])
room_charge = extra_hours * 1500
if extra_hours > 20:
room_charge = 20 * 1500 + (extra_hours - 20) * 1200
# guest passes, first one free for offices
if member.plan == "office":
billable_guests = max(0, usage.guest_passes - 1)
else:
billable_guests = usage.guest_passes
guest_charge = billable_guests * 800
# VAT, rounded half up to the cent
net = base + room_charge + guest_charge
vat = (net * vat_percent + 50) // 100
return net + vat
print(monthly_invoice_cents(Member("office", True), Usage(34, 3), 20))<?php
final class Member
{
public function __construct(public readonly string $plan, public readonly bool $annual) {}
}
final class Usage
{
public function __construct(public readonly int $roomHours, public readonly int $guestPasses) {}
}
const PLAN_CENTS = ['hot-desk' => 19000, 'fixed-desk' => 29000, 'office' => 65000];
const INCLUDED_ROOM_HOURS = ['hot-desk' => 2, 'fixed-desk' => 5, 'office' => 10];
function monthlyInvoiceCents(Member $member, Usage $usage, int $vatPercent): int
{
// plan fee, 10% off for annual commitment
$base = PLAN_CENTS[$member->plan];
if ($member->annual) {
$base = intdiv($base * 9, 10);
}
// meeting rooms beyond the allowance, cheaper after 20 extra hours
$extraHours = max(0, $usage->roomHours - INCLUDED_ROOM_HOURS[$member->plan]);
$roomCharge = $extraHours * 1500;
if ($extraHours > 20) {
$roomCharge = 20 * 1500 + ($extraHours - 20) * 1200;
}
// guest passes, first one free for offices
$billableGuests = $member->plan === 'office' ? max(0, $usage->guestPasses - 1) : $usage->guestPasses;
$guestCharge = $billableGuests * 800;
// VAT, rounded half up to the cent
$net = $base + $roomCharge + $guestCharge;
$vat = intdiv($net * $vatPercent + 50, 100);
return $net + $vat;
}
echo monthlyInvoiceCents(new Member('office', true), new Usage(34, 3), 20), PHP_EOL;After
type Plan = "hot-desk" | "fixed-desk" | "office";
interface Member {
plan: Plan;
annual: boolean;
}
interface Usage {
roomHours: number;
guestPasses: number;
}
const PLAN_CENTS: Record<Plan, number> = { "hot-desk": 19000, "fixed-desk": 29000, office: 65000 };
const INCLUDED_ROOM_HOURS: Record<Plan, number> = { "hot-desk": 2, "fixed-desk": 5, office: 10 };
class MonthlyInvoice {
constructor(
private readonly member: Member,
private readonly usage: Usage,
private readonly vatPercent: number,
) {}
execute(): number {
const net = this.planCharge() + this.roomCharge() + this.guestCharge();
return net + this.vat(net);
}
private planCharge(): number {
const listPrice = PLAN_CENTS[this.member.plan];
return this.member.annual ? Math.floor((listPrice * 9) / 10) : listPrice;
}
private roomCharge(): number {
const extraHours = Math.max(0, this.usage.roomHours - INCLUDED_ROOM_HOURS[this.member.plan]);
if (extraHours <= 20) {
return extraHours * 1500;
}
return 20 * 1500 + (extraHours - 20) * 1200;
}
private guestCharge(): number {
const billableGuests =
this.member.plan === "office" ? Math.max(0, this.usage.guestPasses - 1) : this.usage.guestPasses;
return billableGuests * 800;
}
private vat(net: number): number {
return Math.floor((net * this.vatPercent + 50) / 100);
}
}
export function monthlyInvoiceCents(member: Member, usage: Usage, vatPercent: number): number {
return new MonthlyInvoice(member, usage, vatPercent).execute();
}
console.log(monthlyInvoiceCents({ plan: "office", annual: true }, { roomHours: 34, guestPasses: 3 }, 20));from dataclasses import dataclass
PLAN_CENTS = {"hot-desk": 19000, "fixed-desk": 29000, "office": 65000}
INCLUDED_ROOM_HOURS = {"hot-desk": 2, "fixed-desk": 5, "office": 10}
@dataclass(frozen=True)
class Member:
plan: str
annual: bool
@dataclass(frozen=True)
class Usage:
room_hours: int
guest_passes: int
class MonthlyInvoice:
def __init__(self, member: Member, usage: Usage, vat_percent: int) -> None:
self._member = member
self._usage = usage
self._vat_percent = vat_percent
def execute(self) -> int:
net = self._plan_charge() + self._room_charge() + self._guest_charge()
return net + self._vat(net)
def _plan_charge(self) -> int:
list_price = PLAN_CENTS[self._member.plan]
return list_price * 9 // 10 if self._member.annual else list_price
def _room_charge(self) -> int:
extra_hours = max(0, self._usage.room_hours - INCLUDED_ROOM_HOURS[self._member.plan])
if extra_hours <= 20:
return extra_hours * 1500
return 20 * 1500 + (extra_hours - 20) * 1200
def _guest_charge(self) -> int:
if self._member.plan == "office":
billable_guests = max(0, self._usage.guest_passes - 1)
else:
billable_guests = self._usage.guest_passes
return billable_guests * 800
def _vat(self, net: int) -> int:
return (net * self._vat_percent + 50) // 100
def monthly_invoice_cents(member: Member, usage: Usage, vat_percent: int) -> int:
return MonthlyInvoice(member, usage, vat_percent).execute()
print(monthly_invoice_cents(Member("office", True), Usage(34, 3), 20))<?php
final class Member
{
public function __construct(public readonly string $plan, public readonly bool $annual) {}
}
final class Usage
{
public function __construct(public readonly int $roomHours, public readonly int $guestPasses) {}
}
const PLAN_CENTS = ['hot-desk' => 19000, 'fixed-desk' => 29000, 'office' => 65000];
const INCLUDED_ROOM_HOURS = ['hot-desk' => 2, 'fixed-desk' => 5, 'office' => 10];
final class MonthlyInvoice
{
public function __construct(
private readonly Member $member,
private readonly Usage $usage,
private readonly int $vatPercent,
) {}
public function execute(): int
{
$net = $this->planCharge() + $this->roomCharge() + $this->guestCharge();
return $net + $this->vat($net);
}
private function planCharge(): int
{
$listPrice = PLAN_CENTS[$this->member->plan];
return $this->member->annual ? intdiv($listPrice * 9, 10) : $listPrice;
}
private function roomCharge(): int
{
$extraHours = max(0, $this->usage->roomHours - INCLUDED_ROOM_HOURS[$this->member->plan]);
if ($extraHours <= 20) {
return $extraHours * 1500;
}
return 20 * 1500 + ($extraHours - 20) * 1200;
}
private function guestCharge(): int
{
$billableGuests = $this->member->plan === 'office'
? max(0, $this->usage->guestPasses - 1)
: $this->usage->guestPasses;
return $billableGuests * 800;
}
private function vat(int $net): int
{
return intdiv($net * $this->vatPercent + 50, 100);
}
}
function monthlyInvoiceCents(Member $member, Usage $usage, int $vatPercent): int
{
return (new MonthlyInvoice($member, $usage, $vatPercent))->execute();
}
echo monthlyInvoiceCents(new Member('office', true), new Usage(34, 3), 20), PHP_EOL;Why it's worth it
What the change buys you.
The old function was hard to split because every block depended on the same three inputs. Once those inputs live on an object as fields, each block can become a method with no parameters, or one parameter for a value computed earlier, such as net in vat. The comments that labelled each block turn into method names: planCharge, roomCharge, guestCharge, vat. execute now reads as a summary of the calculation in two lines.
The object also gives the calculation room to grow. If Deskhive adds a late-payment fee or a referral credit, you add one method and one term in execute instead of another commented block in the middle of a long function. If a later step needs an intermediate result, you can store it in a field instead of threading it through return values.
Callers are untouched. monthlyInvoiceCents keeps its signature and simply creates a MonthlyInvoice and runs it, so the refactoring stays inside one module. All arithmetic is in integer cents, and the TypeScript, Python and PHP versions use the same truncating division and half-up VAT rounding. For the sample office member with 34 room hours and 3 guest passes, all three print 106920 both before and after.
- Each step of the calculation becomes a small, named method that you can read and change on its own.
- Shared inputs live in fields, so extracted steps do not need long parameter lists.
- The original function signature stays the same, so callers and their tests keep working.
- New steps, such as an extra fee or credit, slot in as one method and one line in
execute. - The command can later grow subclasses or hooks for variations without touching callers.
Careful with
- Do not apply this to short functions. A class with one method and a wrapper adds indirection that a plain function would not need.
- Keep the command single-use. If
executemutates fields, calling it twice on the same object can give a different answer; creating a fresh instance per call avoids that. - Avoid exposing the step methods publicly just to test them. Test through
executeor the wrapper, and only split out a separate class if a step deserves its own tests. - If the steps stop sharing state after the cleanup, consider Replace Command with Function and fold it back into plain functions.
Step by step
Small, safe steps, with the tests passing after each.
Make sure tests cover the function: at least one case per plan, annual on and off, room hours under and over the 20 extra-hour threshold, and an office with zero and several guest passes.
Create an empty class named after what the function produces, here
MonthlyInvoice, with a constructor that takes the function's parameters and stores them in private, read-only fields.Add an
executemethod and copy the entire function body into it unchanged, replacing parameter references with field references. Run the tests against the class directly.Change the original function so it only builds the command and returns
execute(). Run the tests; callers should see no difference.Pick the first commented block and use Extract Function to move it into a private method that reads fields instead of taking parameters. Replace the block with a call and run the tests.
Repeat for each remaining block, one at a time, running the tests after each extraction. Pass a value as an argument only when it is computed inside
execute, likenet.Delete the comments that only restated what a method name now says, and tidy
executeso it reads as a short summary. Run the tests one last time.
Smells it removes
Smells this refactoring helps remove.
Common questions
Short answers to the usual doubts.
How is this different from Extract Function?
Extract Function pulls a block into a standalone function, which works well when the block needs few inputs. When many blocks share the same inputs or intermediate values, each extracted function needs those passed in again. Replace Function with Command first gives the calculation an object to hold that shared context, after which Extract Function produces methods with short or empty parameter lists.
Is this the Command design pattern?
It borrows the shape: an object that wraps one operation behind an execute method. In this refactoring the goal is structural, to break up a long function. The behavioural extras of the pattern, such as queuing, undo or logging of commands, are optional and only worth adding if you actually need them.
Should I remove the wrapper function afterwards?
Usually not. Keeping monthlyInvoiceCents means callers do not need to know a class exists, and you can change the internals freely. Remove the wrapper only if callers genuinely need the object itself, for example to configure it before running or to inspect intermediate results.
When should I reverse this refactoring?
When the command no longer earns its keep. If after cleanup execute is short and the steps barely share state, Replace Command with Function brings it back to a plain function and removes the extra class.
How would I explain this in an interview?
Describe the trigger: a long function whose blocks all depend on the same inputs, so extracting helpers would bloat parameter lists. Then outline the moves: wrap the function in a class, move parameters to fields, move the body into execute, keep the old function as a delegating wrapper, and extract one block at a time with tests passing after each step.