November 25, 20269 minutes
Two dates passed separately, nine times, until one call swaps them and two families book the same cottage. Learn to spot data clumps and give them a name.
Two families arrive at the same holiday cottage on the same afternoon, and both of them have a confirmation email. Nothing in the code looks wrong. The dates are right. They were passed in the wrong order. That’s the smell called Data Clumps.
Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.
Fern Cottage is booked from the 10th to the 14th of July by the Smiths. The Lees ask for the 12th to the 15th, and they get a confirmation. Here’s the call that checked it:
if (bookings.isFree(fern, checkOut, checkIn)) {
bookings.confirm(guest, checkIn, checkOut);
}Check-out sits where check-in belongs. Search the project for that pair of dates and you find it
in nine method signatures across four classes: isFree, price, confirm, cancelFee,
cleaningDay, invoice, reminder, calendarEntry and review. Two values that always travel
together, carried separately.
Think about a pair of socks on laundry day. They go from the drawer to the washer, to the dryer, and into the suitcase. Carry them loose, and sooner or later one goes missing, or it comes back with the wrong partner.
In code, a data clump is the same small group of values turning up together again and again:
in signatures, in fields, side by side. Martin Fowler and Kent Beck describe it in Refactoring:
the same few data items keep hanging around together, as fields in several classes and as
parameters in many method signatures (paraphrased). Our pair of socks is checkIn and checkOut.
Here’s the booking class. To be fair, it’s good code. The dates are real date types, not strings.
isFree checks every existing booking for an overlap; price counts the nights and multiplies by
the nightly rate.
class Bookings {
boolean isFree(Cottage c, LocalDate checkIn,
LocalDate checkOut) {
for (Booking b : c.bookings()) {
if (checkIn.isBefore(b.checkOut())
&& b.checkIn().isBefore(checkOut)) {
return false;
}
}
return true;
}
int price(Cottage c, LocalDate checkIn,
LocalDate checkOut) {
long nights = DAYS.between(checkIn, checkOut);
return (int) nights * c.nightlyRate();
}
}Read one method at a time, and each one is fine. The smell isn’t in any line. It’s in the pattern between them.
What does the pattern cost you? Three things.
Swaps compile. Both values are LocalDates, so the compiler can’t tell them apart. Swapped,
the Lees’ request runs from the 15th back to the 12th. Is the 15th before the 14th? No. So
isFree says yes, and Fern Cottage is double-booked.
The rules repeat. The number of nights is worked out in three different classes, and one of them adds one. The rule that check-out comes after check-in is tested in two places; the other seven trust their callers.
Changes ripple. The owner wants arrival and departure times, not just dates. That’s nine signatures to edit.
Four tells:
pickupLat and
pickupLon.Take away check-out, and a check-in on its own is not a booking: that’s a lone sock. Take away the number of guests, and the dates still make perfect sense. So guests travels with the dates, but it’s not part of the clump.
Check-in and check-out aren’t two things that happen to be passed together. They’re one thing
with no name yet: a stay. Fowler’s own example of this smell has the same shape: a start and
an end, waiting to become a range. Give it a name, and every signature shrinks: each pair of
dates becomes a single Stay.
If they travel together, give them a name.
The refactoring is called Introduce Parameter Object. In modern Java, the object can be a
record (final since Java 16): it gives you the fields, the accessors, equals, hashCode and
toString from one line. The compact constructor checks the rule once: check-out must come after
check-in. Every Stay that exists has passed that check.
record Stay(LocalDate checkIn, LocalDate checkOut) {
Stay {
if (!checkOut.isAfter(checkIn)) {
throw new IllegalArgumentException(
"check-out must be after check-in");
}
}
}Now the signatures take a stay. isFree and price each lose a parameter, and so do the other
seven.
class Bookings {
boolean isFree(Cottage c, Stay stay) {
for (Booking b : c.bookings()) {
if (stay.overlaps(b.stay())) {
return false;
}
}
return true;
}
int price(Cottage c, Stay stay) {
return (int) stay.nights() * c.nightlyRate();
}
}And the swap? Building a stay with check-out first, new Stay(checkOut, checkIn), now throws
IllegalArgumentException: check-out must be after check-in the moment it’s built. The bug fails
at the door, not at the cottage.
Fields can clump too. The Booking class held the same two dates as fields, so now it holds one
Stay. For fields, the same move is called Extract Class. Fowler suggests starting with the
fields: once the class exists, the parameter lists have something to be replaced with.
Now the stay has a home for the rules that were scattered around it. nights moves in, and so
does overlaps. The three copies of the nights calculation become one, and the stray + 1 is
gone, because there’s nowhere left to put it.
record Stay(LocalDate checkIn, LocalDate checkOut) {
Stay {
if (!checkOut.isAfter(checkIn)) {
throw new IllegalArgumentException(
"check-out must be after check-in");
}
}
long nights() {
return DAYS.between(checkIn, checkOut);
}
boolean overlaps(Stay other) {
return checkIn.isBefore(other.checkOut)
&& other.checkIn.isBefore(checkOut);
}
}This is the part people skip. They make a holder with two getters, and stop there. Fowler’s point is that the interesting work starts when behavior moves into the new object. A bag of getters is only half the fix (and on its own it becomes another smell, Data Class).
And two values are enough. Fowler notes that replacing even two fields with one object pays off.
overlaps treats a stay as half-open: the morning you leave isn’t a night you stay. A guest
leaving on the 14th and one arriving on the 14th don’t overlap, which is exactly what a cleaner
wants.
Here’s a second clump, from a delivery app. An order has four doubles:
class Order {
double pickupLat;
double pickupLon;
double dropOffLat;
double dropOffLon;
}The shared prefixes are the clump announcing itself. And four doubles in a row are four chances to
swap latitude and longitude. Extract Class gives you a GeoPoint. It checks its own range, so a
latitude of 200 is rejected on the spot:
record GeoPoint(double lat, double lon) {
GeoPoint {
if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
throw new IllegalArgumentException("not on Earth");
}
}
}
class Order {
GeoPoint pickup;
GeoPoint dropOff;
}The order now holds two points instead of four numbers, and the distance calculation has an
obvious new home: pickup.distanceKm(dropOff).
Data Clumps has two close neighbors, and they’re easy to mix up.
isFree takes only three parameters,
but it’s still clumped. A clump is often the reason lists are long, and fixing it shortens many
lists at once.They often come together: four doubles in a row on a delivery order are all three at once.
| Smell | What repeats or grows | Typical fix |
|---|---|---|
| Data Clumps | the same group of values, in many places | Introduce Parameter Object, Extract Class |
| Long Parameter List | the number of parameters of one method | Preserve Whole Object, Replace Parameter with Query, Introduce Parameter Object |
| Primitive Obsession | a domain value kept as a raw double, int or String | Replace Primitive with Object |
quote(Stay stay, int guests) takes a stay and a guest count, and that’s exactly right.Stay at the
boundary.A data clump is a group of values that travels together, but gets carried loose. Test it by taking one away: if the rest makes no sense, it’s one thing. Name it with Introduce Parameter Object or Extract Class, check the rule once, and let the behavior move in. Swaps fail at the door, the rules live in one place, and nine signatures get shorter.
Checklist before you open a pull request:
If they travel together, give them a name.
Related lessons:
Large Class (clumped fields are often the seams
to split a big class along),
Feature Envy (once Stay exists,
methods that keep reaching into its dates should move into it), and
Long Method (Introduce Parameter Object shortens long methods too).