Data Clumps

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.

Two families, one cottage

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.

The pair LocalDate checkIn, LocalDate checkOut appears in nine signatures across four classes: Bookings (isFree, price, confirm), Billing (cancelFee, invoice), Mailer (reminder, review) and Calendar (cleaningDay, calendarEntry). The pair LocalDate checkIn, LocalDate checkOut appears in nine signatures across four classes: Bookings (isFree, price, confirm), Billing (cancelFee, invoice), Mailer (reminder, review) and Calendar (cleaningDay, calendarEntry).
One pair of dates, nine signatures, four classes.

Socks in the laundry

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.

The analogy mapped onto code: a pair of socks is checkIn and checkOut; carrying them loose is passing them as separate parameters; a lost or mismatched sock is a forgotten or swapped argument; rolling the pair into a ball is a Stay type. The analogy mapped onto code: a pair of socks is checkIn and checkOut; carrying them loose is passing them as separate parameters; a lost or mismatched sock is a forgotten or swapped argument; rolling the pair into a ball is a Stay type.
The laundry, mapped onto the code.

What it looks like

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.

Why it hurts

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.

One change request, times not just dates, forces LocalDate to become LocalDateTime in all nine signatures: isFree, price, confirm, cancelFee, invoice, reminder, review, cleaningDay and calendarEntry. One change request, times not just dates, forces LocalDate to become LocalDateTime in all nine signatures: isFree, price, confirm, cancelFee, invoice, reminder, review, cleaningDay and calendarEntry.
One change request, nine signatures.

How to spot it

Four tells:

  1. The same group of parameters in several signatures.
  2. The same group of fields in several classes, often sharing a prefix, like pickupLat and pickupLon.
  3. The same little calculation sitting next to the group, like those nights.
  4. The take-one-away test. Take one value away. If the rest no longer makes sense, they belong together. Fowler and Beck call it a sure sign of an object waiting to be born (paraphrased).

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.

The take-one-away test. Remove one value from the group. If the remaining values no longer make sense, it is a clump: make a type. If they still make sense, the value only travels along and should stay separate. The take-one-away test. Remove one value from the group. If the remaining values no longer make sense, it is a clump: make a type. If they still make sense, the value only travels along and should stay separate.
Take one away. If the rest makes no sense, it's a clump.

The key insight: it’s a stay

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 fix: Introduce Parameter Object

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.

Before and after. Before: Bookings, Billing and Mailer each take checkIn and checkOut separately and each computes nights. After: each takes one Stay, and Stay owns the check-out-after-check-in rule, nights and overlaps. Before and after. Before: Bookings, Billing and Mailer each take checkIn and checkOut separately and each computes nights. After: each takes one Stay, and Stay owns the check-out-after-check-in rule, nights and overlaps.
Before: the pair everywhere. After: one type that owns its rules.

The behavior moves in

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.

A second example: four doubles on an order

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

Class diagram after Extract Class: Order has two GeoPoint fields, pickup and dropOff. GeoPoint has lat and lon, validates its range and is the home for distanceKm. Class diagram after Extract Class: Order has two GeoPoint fields, pickup and dropOff. GeoPoint has lat and lon, validates its range and is the home for distanceKm.
Two points instead of four numbers.

Commonly confused: long parameter list and primitive obsession

Data Clumps has two close neighbors, and they’re easy to mix up.

  • Long Parameter List is one method asking for too much. A clump is a group that repeats across many methods. 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.
  • Primitive Obsession is a single value that deserves its own type. A clump is several values that belong together. Fowler calls groups of primitives that appear together data clumps.

They often come together: four doubles in a row on a delivery order are all three at once.

Three neighboring smells by symptom: one method that asks for too much is Long Parameter List; a group of values that repeats across methods or classes is Data Clumps; one value with no type of its own is Primitive Obsession. Four doubles in a row on an order show all three. Three neighboring smells by symptom: one method that asks for too much is Long Parameter List; a group of values that repeats across methods or classes is Data Clumps; one value with no type of its own is Primitive Obsession. Four doubles in a row on an order show all three.
Same family, different symptoms.
SmellWhat repeats or growsTypical fix
Data Clumpsthe same group of values, in many placesIntroduce Parameter Object, Extract Class
Long Parameter Listthe number of parameters of one methodPreserve Whole Object, Replace Parameter with Query, Introduce Parameter Object
Primitive Obsessiona domain value kept as a raw double, int or StringReplace Primitive with Object

When it’s not a smell

  • Coincidence, not a concept. Values can happen to appear together without being one thing. A sock and a shoe go out the door together, but you don’t wash them as one. That’s the number of guests: quote(Stay stay, int guests) takes a stay and a guest count, and that’s exactly right.
  • At the edges of the system, flat is fine. A booking form posts two date fields, a JSON payload has two strings, a database row has two columns. The controller turns them into a Stay at the boundary.
  • Don’t tie a general helper to your domain. A shared date library shouldn’t need to know what a stay is. Passing the whole object can create a dependency you don’t want.
Should this group become a type? If one value makes sense without the others, keep them separate. If the code is at the system boundary, such as a form, JSON or a database row, keep it flat and convert there. If the function is a general helper that must not depend on the domain, keep plain values. Otherwise give the group a name. Should this group become a type? If one value makes sense without the others, keep them separate. If the code is at the system boundary, such as a form, JSON or a database row, keep it flat and convert there. If the function is a general helper that must not depend on the domain, keep plain values. Otherwise give the group a name.
Group what is one thing; leave coincidences and boundaries alone.

Recap

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.

Recap chain: spot the group, take one away, name it, move the behavior in. Recap chain: spot the group, take one away, name it, move the behavior in.
If they travel together, give them a name.

Checklist before you open a pull request:

  • Does the same pair or trio of parameters appear in more than one signature?
  • Do two classes share a set of fields with the same prefix?
  • Is the same small calculation repeated next to those values?
  • Would one value be meaningless without the others?
  • If you made the type, does it check its own rule and own its own calculations?

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

Further reading