Data Class

November 26, 20269 minutes

Three classes decide whether a loan is overdue, and they disagree. Learn to spot a Data Class, move behavior to where the data lives, and know when a plain data carrier is fine.

A library app tracks every loan. The Loan class holds a book, a member, a borrowed date, a due date and a return date. Three other classes need one answer: is this loan overdue? The loan service, the reminder job and the fine report each work it out. They each read the dates, and decide for themselves, and each one decides a little differently. So who owns the rule for overdue? The answer is a smell called Data Class.

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.

Three classes, three answers

Look at what the three callers do on the day a book is due. The loan service says it isn’t overdue yet. The reminder job says it is. And the fine report fines only loans that are still out, so a book returned late pays nothing. One rule, three copies, three answers.

The filing cabinet and the clerk

Picture a filing cabinet in the middle of an office. Anyone can open a drawer, take out a file, and put it back wherever they like. Nobody owns it, so everyone keeps their own rules for reading the files. One person counts a Friday return as late. Another doesn’t.

Now picture a records clerk instead. The clerk keeps the files, and answers questions about them. Is this loan overdue? Ask the clerk.

The Loan class is the cabinet. The three callers are the people with their own rules. And the clerk is the class we haven’t written yet. A data class is a class that only holds data: fields, getters and setters, and little else.

The naive version

Here’s the Loan class: five private fields, and a getter and setter for most of them.

class Loan {
    private Book book;
    private Member member;
    private LocalDate borrowedOn;
    private LocalDate dueOn;
    private LocalDate returnedOn;

    public Member getMember() { return member; }
    public void setMember(Member member) { this.member = member; }
    public LocalDate getDueOn() { return dueOn; }
    public void setDueOn(LocalDate dueOn) { this.dueOn = dueOn; }
    public LocalDate getReturnedOn() { return returnedOn; }
    public void setReturnedOn(LocalDate day) { this.returnedOn = day; }
    // ... and the same pair for book and borrowedOn
}

It’s easy to read. The fields are private, so it even looks encapsulated, and it’s a perfectly reasonable place to start. But look at what the class can do. It hands out its dates, and it takes new ones in. It can’t answer a single question about them.

Classes like this usually start innocently. Someone pulls related fields into a class to fix Primitive Obsession, or the design says managers do the work and this class just holds the data.

Why it hurts

Here’s how the loan service decides. It checks that the loan hasn’t come back, and that today is after the due date:

class LoanService {
    boolean isOverdue(Loan loan, LocalDate today) {
        return loan.getReturnedOn() == null
            && today.isAfter(loan.getDueOn());
    }
}

The reminder job asks almost the same question, but it counts the due date itself as overdue:

class ReminderJob {
    void remind(Loan loan, LocalDate today) {
        if (loan.getReturnedOn() == null
                && !today.isBefore(loan.getDueOn())) {
            send(loan.getMember(), "Your book is due");
        }
    }
}

And the fine report only fines loans that are still out. A book returned late slips through for free:

class FineReport {
    double fine(Loan loan, LocalDate today) {
        if (loan.getReturnedOn() != null) return 0;
        long days = ChronoUnit.DAYS.between(loan.getDueOn(), today);
        return days > 0 ? days * 0.25 : 0;
    }
}

(The fine rate is a made-up example value.) Three copies of one rule, and the copies disagree. Add a grace day, and you have to hunt through all three. That’s the Shotgun Surgery smell, with a data class as its cause.

There’s a second risk. Every setter is open, so any class can change a due date, and nobody can say who did.

Before and after. Before: LoanService, ReminderJob and FineReport each read the Loan fields and keep their own copy of the rule, so three callers point at one data-only Loan. After: the same three callers ask the Loan, which owns the overdue and fine rules, with one call each. Before and after. Before: LoanService, ReminderJob and FineReport each read the Loan fields and keep their own copy of the rule, so three callers point at one data-only Loan. After: the same three callers ask the Loan, which owns the overdue and fine rules, with one call each.
Three copies of one rule become one rule inside Loan.

How to spot it

  1. Only getters and setters. Every method in the class is one or the other.
  2. Callers compute from its fields. They read three or four fields, then do the maths themselves.
  3. The same expression, copied into more than one class.
  4. Setters on values that should be set once, like a due date.

Public fields count too. A class with no setters, just open fields, is the same smell with the doors off. The course reference page describes the smell the same way: a class whose job is to hold data and nothing more.

The key insight: behavior goes where the data lives

So what’s wrong with holding data? Nothing, until the rules about that data live somewhere else. The insight is a simple one: behavior that only uses a class’s data belongs in that class. Is this loan overdue? That’s a question about a loan. So the loan should answer it.

Think of it as asking the clerk, instead of reading the files yourself. You get an answer, and you never need to know the filing system.

You could put the rule in a helper, a LoanRules class. That only moves it. The rule still sits away from the data, and the loan is still all cabinet.

Put the behavior where the data lives.

The fix, step by step

The fix takes three steps.

First, close the doors. Encapsulate Field made the fields private, but the setters still let anyone rewrite them. So we apply Remove Setting Method. The dates are set once, in the constructor. The only change that ever happens is a book coming back, so that gets its own method:

class Loan {
    private final Book book;
    private final Member member;
    private final LocalDate borrowedOn;
    private final LocalDate dueOn;
    private LocalDate returnedOn;

    Loan(Book book, Member member, LocalDate borrowedOn) {
        this.book = book;
        this.member = member;
        this.borrowedOn = borrowedOn;
        this.dueOn = borrowedOn.plusDays(14);
    }

    void markReturned(LocalDate day) { this.returnedOn = day; }
}

(Closing the doors is what Encapsulation is about.) The fourteen-day loan period is a made-up example value.

Second, apply Move Method. The overdue rule leaves the loan service and moves into the loan, as isOverdue. The fine moves in too. It counts the days from the due date to the return date, or to today if the book is still out:

class Loan {
    // fields and constructor as before

    boolean isOverdue(LocalDate today) {
        return returnedOn == null && today.isAfter(dueOn);
    }

    double fine(LocalDate today) {
        LocalDate end = (returnedOn == null) ? today : returnedOn;
        long daysLate = ChronoUnit.DAYS.between(dueOn, end);
        return Math.max(daysLate, 0) * 0.25;
    }

    Member member() { return member; }
}

Third, the three classes shrink. Each one just asks the loan:

// LoanService
boolean overdue = loan.isOverdue(today);

// ReminderJob
if (loan.isOverdue(today)) {
    send(loan.member(), "Your book is due");
}

// FineReport
double fine = loan.fine(today);

Move in small steps. If a caller’s method does more than the rule, pull the rule out with Extract Method first, then move it, and run the tests between steps.

Class diagram of the refactored design. Loan has private fields book, member, borrowedOn, dueOn and returnedOn, and public methods isOverdue, fine, markReturned and member. LoanService, ReminderJob and FineReport each depend on Loan by asking it. Class diagram of the refactored design. Loan has private fields book, member, borrowedOn, dueOn and returnedOn, and public methods isOverdue, fine, markReturned and member. LoanService, ReminderJob and FineReport each depend on Loan by asking it.
Loan keeps its data and answers questions about it.

A second example: the shopping cart

An exposed list is the same smell. Here’s a shopping cart with a public list of items, and checkout code that loops over the list to add up prices:

class Cart {
    public List<Item> items = new ArrayList<>();
}

// CheckoutService
double total = 0;
for (Item item : cart.items) {
    total += item.price() * item.quantity();
}

Anyone can add to that list, or remove from it, without the cart knowing. And the total is work the cart should be doing. So apply Move Method to bring the total in, and Encapsulate Collection to hide the list:

class Cart {
    private final List<Item> items = new ArrayList<>();

    void add(Item item) { items.add(item); }

    double total() {
        double sum = 0;
        for (Item item : items) {
            sum += item.price() * item.quantity();
        }
        return sum;
    }

    List<Item> items() { return Collections.unmodifiableList(items); }
}

Callers now call add, and read a list that can’t be changed. The cart keeps its own files. And a rule like a limit per item now has a home: it lives in add, once, and no caller can skip it.

Commonly confused: Data Class and Feature Envy

Data class has a twin. Feature Envy is a method that spends its time on another class’s data. Data class is the class at the other end. They’re two views of one misplaced method: the overdue method envies the loan, and the loan is a data class.

So one refactoring cures both. Move the method to the data, and the envy ends, and the class gains a purpose.

The course reference page gives another case. A calculateVolume method sat in PartStudio, but it only used a Plane’s data. Moving it into Plane ended the smell.

Feature Envy and Data Class as two views of one problem. The method LoanService.isOverdue reaches into Loan's data, which is Feature Envy; Loan has no behavior, which is Data Class. After Move Method, the method lives in Loan and both smells are gone. Feature Envy and Data Class as two views of one problem. The method LoanService.isOverdue reaches into Loan's data, which is Feature Envy; Loan has no behavior, which is Data Class. After Move Method, the method lives in Loan and both smells are gone.
One Move Method cures both smells.

Myths, and when to leave it

One myth to drop: that records and data transfer objects are always data classes, and so always bad. They aren’t. A data carrier at a boundary is fine on purpose. An API response, a database row, a record holding a value: they exist to move data.

record LoanDto(String title, String member, LocalDate dueOn) { }

The smell isn’t a class with no methods. It’s domain rules living outside the data they need. A getter hands out a value. A method like isOverdue answers a question. Only the second one moves the rule. So leave it alone when it’s a boundary object, a simple value record, or generated code. If nothing computes from it, there is nothing to move. (The course reference page lists no cases to ignore; this list is our own judgment.)

And a record can carry behavior too. Give a loan record an isOverdue method, and it’s still a record. Being a record is a way to hold data, not an excuse to keep the rules elsewhere.

Decision flow. Does the class only hold data? If not, it is fine. If so, is it a boundary carrier such as a DTO, a database row, a value record or generated code? If yes, leave it. If not, do callers compute from its fields? If yes, move the methods in, remove setters and encapsulate collections. If no, there is nothing to move. Decision flow. Does the class only hold data? If not, it is fine. If so, is it a boundary carrier such as a DTO, a database row, a value record or generated code? If yes, leave it. If not, do callers compute from its fields? If yes, move the methods in, remove setters and encapsulate collections. If no, there is nothing to move.
When to refactor, and when to leave it.

Recap

A data class holds data, while everyone else makes the decisions about it. Spot it by its getters and setters, and by copies of one rule. Fix it by removing setters, moving the methods in, and hiding collections. And remember its twin: one move cures data class and feature envy together.

Recap chain: all cabinet and no clerk; spot copies of one rule; fix by moving the methods in; twin is Feature Envy. Recap chain: all cabinet and no clerk; spot copies of one rule; fix by moving the methods in; twin is Feature Envy.
Put the behavior where the data lives.

Checklist:

  • Is every method of the class a getter or a setter?
  • Do callers read several of its fields and compute the same thing?
  • Does a setter exist for a value that should be set once?
  • Is a collection exposed for anyone to change?
  • Is it really a boundary carrier (DTO, row, value record, generated code) that should stay plain?

Put the behavior where the data lives.

Further reading