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.
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
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.
Checklist:
Put the behavior where the data lives.