Preserve Whole Object is a small refactoring with a large effect on readability. When a caller reads three or four fields from an object only to pass them straight into a method, you pass the object itself and let the method read what it needs.
This guide uses a parcel locker service. A courier app decides which compartment in a locker bank can take a given parcel, and the check currently receives the parcel's dimensions and weight as four loose numbers. You will change the signature in small steps, keep the tests green after each one, and end with a method that takes a Parcel.
The problem
A situation where the obvious design starts to hurt.
Compartment.accepts takes width, height, depth and weight as separate numbers. Every caller has to unpack a Parcel first, in the right order, with nothing stopping it from swapping height and depth. The four values always travel together, which is a data clump, and the signature is a long parameter list that grows every time the fit rule needs another fact about the parcel.
Suppose the business adds a rule that fragile parcels may only go into padded compartments. You would add a fifth parameter and then edit every call site, even though each caller already holds the parcel that knows whether it is fragile.
Before and after
The same code, before and after the change.
Before
class Parcel {
constructor(
readonly id: string,
readonly widthCm: number,
readonly heightCm: number,
readonly depthCm: number,
readonly weightKg: number,
) {}
}
class Compartment {
constructor(
readonly code: string,
readonly maxWidthCm: number,
readonly maxHeightCm: number,
readonly maxDepthCm: number,
readonly maxWeightKg: number,
) {}
accepts(widthCm: number, heightCm: number, depthCm: number, weightKg: number): boolean {
return (
widthCm <= this.maxWidthCm &&
heightCm <= this.maxHeightCm &&
depthCm <= this.maxDepthCm &&
weightKg <= this.maxWeightKg
);
}
}
function assignCompartment(parcel: Parcel, compartments: Compartment[]): string | null {
const width = parcel.widthCm;
const height = parcel.heightCm;
const depth = parcel.depthCm;
const weight = parcel.weightKg;
for (const compartment of compartments) {
if (compartment.accepts(width, height, depth, weight)) {
return compartment.code;
}
}
return null;
}
const lockerB7 = [
new Compartment("B7-S1", 30, 10, 40, 5),
new Compartment("B7-M1", 40, 25, 60, 15),
];
console.log(assignCompartment(new Parcel("PX-1042", 35, 20, 50, 8), lockerB7)); // B7-M1from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Parcel:
id: str
width_cm: float
height_cm: float
depth_cm: float
weight_kg: float
@dataclass(frozen=True)
class Compartment:
code: str
max_width_cm: float
max_height_cm: float
max_depth_cm: float
max_weight_kg: float
def accepts(self, width_cm: float, height_cm: float, depth_cm: float, weight_kg: float) -> bool:
return (
width_cm <= self.max_width_cm
and height_cm <= self.max_height_cm
and depth_cm <= self.max_depth_cm
and weight_kg <= self.max_weight_kg
)
def assign_compartment(parcel: Parcel, compartments: list[Compartment]) -> Optional[str]:
width = parcel.width_cm
height = parcel.height_cm
depth = parcel.depth_cm
weight = parcel.weight_kg
for compartment in compartments:
if compartment.accepts(width, height, depth, weight):
return compartment.code
return None
locker_b7 = [
Compartment("B7-S1", 30, 10, 40, 5),
Compartment("B7-M1", 40, 25, 60, 15),
]
print(assign_compartment(Parcel("PX-1042", 35, 20, 50, 8), locker_b7)) # B7-M1<?php
final class Parcel
{
public function __construct(
public readonly string $id,
public readonly float $widthCm,
public readonly float $heightCm,
public readonly float $depthCm,
public readonly float $weightKg,
) {}
}
final class Compartment
{
public function __construct(
public readonly string $code,
public readonly float $maxWidthCm,
public readonly float $maxHeightCm,
public readonly float $maxDepthCm,
public readonly float $maxWeightKg,
) {}
public function accepts(float $widthCm, float $heightCm, float $depthCm, float $weightKg): bool
{
return $widthCm <= $this->maxWidthCm
&& $heightCm <= $this->maxHeightCm
&& $depthCm <= $this->maxDepthCm
&& $weightKg <= $this->maxWeightKg;
}
}
function assignCompartment(Parcel $parcel, array $compartments): ?string
{
$width = $parcel->widthCm;
$height = $parcel->heightCm;
$depth = $parcel->depthCm;
$weight = $parcel->weightKg;
foreach ($compartments as $compartment) {
if ($compartment->accepts($width, $height, $depth, $weight)) {
return $compartment->code;
}
}
return null;
}
$lockerB7 = [
new Compartment('B7-S1', 30, 10, 40, 5),
new Compartment('B7-M1', 40, 25, 60, 15),
];
echo assignCompartment(new Parcel('PX-1042', 35, 20, 50, 8), $lockerB7) ?? 'none', PHP_EOL; // B7-M1After
class Parcel {
constructor(
readonly id: string,
readonly widthCm: number,
readonly heightCm: number,
readonly depthCm: number,
readonly weightKg: number,
) {}
}
class Compartment {
constructor(
readonly code: string,
readonly maxWidthCm: number,
readonly maxHeightCm: number,
readonly maxDepthCm: number,
readonly maxWeightKg: number,
) {}
accepts(parcel: Parcel): boolean {
return (
parcel.widthCm <= this.maxWidthCm &&
parcel.heightCm <= this.maxHeightCm &&
parcel.depthCm <= this.maxDepthCm &&
parcel.weightKg <= this.maxWeightKg
);
}
}
function assignCompartment(parcel: Parcel, compartments: Compartment[]): string | null {
for (const compartment of compartments) {
if (compartment.accepts(parcel)) {
return compartment.code;
}
}
return null;
}
const lockerB7 = [
new Compartment("B7-S1", 30, 10, 40, 5),
new Compartment("B7-M1", 40, 25, 60, 15),
];
console.log(assignCompartment(new Parcel("PX-1042", 35, 20, 50, 8), lockerB7)); // B7-M1from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Parcel:
id: str
width_cm: float
height_cm: float
depth_cm: float
weight_kg: float
@dataclass(frozen=True)
class Compartment:
code: str
max_width_cm: float
max_height_cm: float
max_depth_cm: float
max_weight_kg: float
def accepts(self, parcel: Parcel) -> bool:
return (
parcel.width_cm <= self.max_width_cm
and parcel.height_cm <= self.max_height_cm
and parcel.depth_cm <= self.max_depth_cm
and parcel.weight_kg <= self.max_weight_kg
)
def assign_compartment(parcel: Parcel, compartments: list[Compartment]) -> Optional[str]:
for compartment in compartments:
if compartment.accepts(parcel):
return compartment.code
return None
locker_b7 = [
Compartment("B7-S1", 30, 10, 40, 5),
Compartment("B7-M1", 40, 25, 60, 15),
]
print(assign_compartment(Parcel("PX-1042", 35, 20, 50, 8), locker_b7)) # B7-M1<?php
final class Parcel
{
public function __construct(
public readonly string $id,
public readonly float $widthCm,
public readonly float $heightCm,
public readonly float $depthCm,
public readonly float $weightKg,
) {}
}
final class Compartment
{
public function __construct(
public readonly string $code,
public readonly float $maxWidthCm,
public readonly float $maxHeightCm,
public readonly float $maxDepthCm,
public readonly float $maxWeightKg,
) {}
public function accepts(Parcel $parcel): bool
{
return $parcel->widthCm <= $this->maxWidthCm
&& $parcel->heightCm <= $this->maxHeightCm
&& $parcel->depthCm <= $this->maxDepthCm
&& $parcel->weightKg <= $this->maxWeightKg;
}
}
function assignCompartment(Parcel $parcel, array $compartments): ?string
{
foreach ($compartments as $compartment) {
if ($compartment->accepts($parcel)) {
return $compartment->code;
}
}
return null;
}
$lockerB7 = [
new Compartment('B7-S1', 30, 10, 40, 5),
new Compartment('B7-M1', 40, 25, 60, 15),
];
echo assignCompartment(new Parcel('PX-1042', 35, 20, 50, 8), $lockerB7) ?? 'none', PHP_EOL; // B7-M1Why it's worth it
What the change buys you.
The four numbers were never independent. They describe one parcel, and the fit rule is a question about that parcel. Passing the object says so in the signature: accepts(parcel) reads as the domain sentence a compartment accepts a parcel.
The call sites shrink and lose the ordering risk. With four numeric parameters of the same type, swapping two of them compiles fine and fails silently. With one typed parameter, there is nothing to swap.
The method also becomes stable against change. If the fit rule later needs a fragile flag or a declared value, accepts reads it from the parcel and no caller has to change. That is the real payoff: the next requirement touches one method instead of every place that unpacks a parcel.
Behaviour is unchanged. The comparisons are the same, evaluated in the same order with the same short-circuiting, so the same compartment is chosen for every input.
- Call sites become one short, readable line with no unpacking boilerplate.
- Swapping two same-typed numeric arguments by mistake is no longer possible.
- New fit rules that need more parcel data change only the method, not its callers.
- The signature states the domain relationship directly: a compartment accepts a parcel.
Careful with
- The callee now depends on the
Parceltype. IfCompartmentlives in a lower-level module that must not know about parcels, introduce a small interface such asDimensionsinstead of coupling the modules. - Do not apply it when the values come from different objects, or when the callee needs only one field. Passing a whole object for a single number hides what the method actually uses.
- Some callers may only have raw numbers, for example a quick quote form before a parcel exists. Either construct a
Parcelthere or keep a separate entry point for that case rather than inventing fake ids. - If the object is mutable, the callee could now modify it. Keep the parameter read-only (readonly fields, frozen dataclass) or make the method's contract explicit.
Step by step
Small, safe steps, with the tests passing after each.
Make sure tests cover
acceptsandassignCompartment, including a parcel that fits no compartment and one that fails only on weight. Run them and confirm they pass.Add a new method
acceptsParcel(parcel: Parcel)onCompartmentwhose body simply calls the old method:return this.accepts(parcel.widthCm, parcel.heightCm, parcel.depthCm, parcel.weightKg). Run the tests.Change one caller,
assignCompartment, to callcompartment.acceptsParcel(parcel). Run the tests.Delete the local variables
width,height,depthandweightinassignCompartment, which are now unused. Run the tests.Repeat for any other caller of the four-argument
accepts, one at a time, running the tests after each change.When nothing calls the old method any more, inline its body into
acceptsParcelso it reads the parcel's fields directly, then delete the old method. Run the tests.Rename
acceptsParceltoacceptswith your IDE's rename refactoring. Run the tests one last time.
Smells it removes
Smells this refactoring helps remove.
Common questions
Short answers to the usual doubts.
Doesn't passing the whole object increase coupling?
It changes it. Before, the callee depended on four numbers and every caller depended on the parcel's internal field layout. After, the callee depends on one type and callers depend on nothing extra. If the dependency on the concrete class is a problem, depend on a narrow interface that exposes just the dimensions and weight.
How is this different from Introduce Parameter Object?
Introduce Parameter Object creates a new class for values that travel together but have no home yet. Preserve Whole Object applies when that object already exists and the caller is pulling values out of it. Here Parcel already existed, so you reuse it.
Should the logic move to Parcel instead, as parcel.fitsIn(compartment)?
Either direction works, and that would be a separate Move Method decision. The rule compares parcel data against compartment limits, so it uses both sides equally. Keep it where the team naturally looks for it and where future rules, such as padded compartments for fragile items, are most likely to be added.
How would I explain this in an interview?
Say that callers were unpacking an object just to pass its fields, which created a long parameter list and a data clump. Then describe the safe path: add a new method that takes the object and delegates to the old one, migrate callers one by one with tests green, inline, delete, rename. Mention the coupling trade-off and when you would use an interface instead.