November 24, 202610 minutes
Every code base has one class that every change goes through. Learn to spot a Large Class, split it along its seams with Extract Class, and give each class one reason to change.
Meet Dave. Dave works at a small concert venue. He runs the box office, the mailing list, and the posters, and he’s the only one who knows how the building works. So every question goes to Dave. And when Dave goes on holiday, nothing moves. Most code bases have a Dave: a class that started small and kept taking on jobs, until every change had to go through it. This code smell is called Large Class.
Prefer to watch? The narrated video covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams and a little extra depth.
Nobody planned it. It just always seemed easier to add one more method to the class that already knew everything. In this lesson we’ll see what a large class looks like, why it hurts, how to spot it, and how to give each job its own class.
Here’s the venue’s app: the ConcertManager class. Eight fields and eight methods, with the
bodies left out:
class ConcertManager {
private String venueName;
private String venueAddress;
private int venueCapacity;
private double ticketPrice;
private int ticketsSold;
private String mailHost;
private String mailSender;
private String posterTemplate;
void sellTicket(String buyer) { ... }
void refund(String buyer) { ... }
boolean isSoldOut() { ... }
double revenue() { ... }
void sendReminders() { ... }
void sendNewsletter() { ... }
String renderPoster() { ... }
String directions() { ... }
}Look at the field names: venue name, venue address, venue capacity. Ticket price and tickets sold. Mail host and mail sender. And a poster template. The methods fall into the same groups: selling, refunds and revenue use the ticket fields; the reminders and the newsletter use the mail fields; the poster uses the template. It’s Dave’s desk, with four in-trays that never mix.
Martin Fowler calls this smell Large Class in Refactoring: a class that’s trying to do too much. You’ll also hear it called a God class, because it knows everything and does everything. Real ones are much bigger than this sketch: dozens of fields, hundreds of methods, thousands of lines.
You can’t hold it in your head. To change one thing, you scroll past everything else.
Changes collide. One developer adds refunds. Another switches the mail provider. A third redesigns the poster. Three unrelated tasks, one file. Merge conflict.
It’s hard to test. To check that a refund gives the money back, this test has to build the whole concert manager, including a mail server and a poster template:
@Test
void refundGivesMoneyBack() {
ConcertManager m = new ConcertManager(
"Blue Hall", "12 Dock Road", 300,
25.0, "smtp.example.com", "noreply@example.com",
"poster.html");
m.sellTicket("ana");
m.refund("ana");
assertEquals(0.0, m.revenue());
}None of that has anything to do with refunds. But the class needs it, so every test needs it. When a test needs a mail server to check some arithmetic, the class is too big.
You can’t reuse any part on its own. Want the box office for a second venue? It comes with the posters attached.
When unrelated changes share one file, they share every risk.
How do you spot a large class? Look for five signals.
Groups of fields. Fields that share a prefix, like venue…, ticket… and mail…, or
that are always used together.
Methods that only use some of the fields. Draw a grid of which method uses which field, and you’ll see islands:
| Method | venue fields | ticket fields | mail fields | poster field |
|---|---|---|---|---|
sellTicket() | capacity | ✓ | ||
refund() | ✓ | |||
isSoldOut() | capacity | ✓ | ||
revenue() | ✓ | |||
sendReminders() | name | ✓ | ||
sendNewsletter() | ✓ | |||
renderPoster() | name | ✓ | ||
directions() | ✓ |
(The venue column is the shared one: several groups need to read the venue. That’s a hint
that Venue becomes a small value object the others hold.)
A vague name. Manager, Processor, Helper, Utils. Or a description that needs the
word and: “manages concerts and tickets and mail and posters”.
Many reasons to change. If ticket rules, email and posters all edit the same class, that’s Divergent Change, also covered in the Shotgun Surgery lesson.
Heavy tests, with a long setup and lots of mocks.
Here’s the rule of thumb: group the fields, and the class falls apart along the seams.
So what’s the fix? It starts with a principle. The Single Responsibility Principle says a class should have one reason to change.
The main refactoring is Extract Class. Take a group of fields and the methods that use them, and move them into a new class with a good name. The old class keeps a reference to the new one and delegates to it.
The venue fields become a Venue record: a name, an address and a capacity. The ticket fields
and their methods become a BoxOffice. It sells tickets, knows when the show is sold out, and
adds up the revenue:
record Venue(String name, String address, int capacity) {}
class BoxOffice {
private final Venue venue;
private final double price;
private int sold;
BoxOffice(Venue venue, double price) {
this.venue = venue;
this.price = price;
}
void sell(String buyer) { ... }
boolean isSoldOut() { return sold >= venue.capacity(); }
double revenue() { return sold * price; }
}The mail fields and methods become a ConcertMailer and the poster template a Poster, in
exactly the same way. It’s like Dave hiring a team: a box office clerk, a mail person and a
poster designer.
One class, one job. Split by reason to change.
What’s left of the old class? A small coordinator. The Concert holds a venue, a box office
and a mailer, and it delegates to them. Selling a ticket is now two lines: the box office
sells, and the mailer sends a confirmation:
class Concert {
private final Venue venue;
private final BoxOffice boxOffice;
private final ConcertMailer mailer;
void sellTicket(String buyer) {
boxOffice.sell(buyer);
mailer.sendConfirmation(buyer);
}
}But watch for leftovers. This revenue method stayed behind in the concert. It only reads the box office’s numbers:
// left behind in Concert: it only reads BoxOffice's data
double revenue() {
return boxOffice.getSold() * boxOffice.getPrice();
}That’s
Feature Envy. So move it home, into the box office,
where the data lives (it’s the revenue() you saw in BoxOffice above). Extract the data,
then move the behavior next to it.
Here’s another shape. Some fields are only used by some of the objects. Festivals have stages
and camping spots; ordinary concerts don’t. So the class carries a flag, isFestival, and
checks it everywhere. For most concerts, those fields just sit there, empty:
class Concert {
private boolean isFestival;
private List<String> stages; // festivals only
private int campingSpots; // festivals only
double ticketPrice() {
return isFestival ? basePrice + campingFee() : basePrice;
}
}The refactoring is Extract Subclass. Move the festival fields and behavior into a
Festival class. The flag disappears, because the type itself tells you:
class Festival extends Concert {
private List<String> stages;
private int campingSpots;
@Override
double ticketPrice() {
return super.ticketPrice() + campingFee();
}
}Only use this when it’s a true is-a relationship. Otherwise, prefer composition (for example a
Concert that holds an optional Camping part). The
Refused Bequest lesson shows what goes wrong when a
subclass doesn’t really want what it inherits.
A field that’s empty for most objects is asking for its own class.
Sometimes you can’t split the class yet. But different clients use different parts of it. The checkout page sells tickets. Reports read the revenue. Marketing sends newsletters.
Extract Interface gives each client a small interface with only the methods it needs. The
checkout page depends on TicketSales, and nothing else:
interface TicketSales {
void sellTicket(String buyer);
boolean isSoldOut();
}
class CheckoutPage {
private final TicketSales sales;
}The class is still big. But each client now sees a small slice, and the interface marks exactly
where the class can be split later: when BoxOffice is extracted, it simply implements
TicketSales, and the checkout page doesn’t change. (This is the Interface Segregation
Principle at work: clients shouldn’t depend on methods they don’t use.)
Here’s a second example, from almost every web app: the user service. It started with sign up and login. Then someone added avatar uploads and image resizing. Then the newsletter. Then an export of personal data, for privacy requests:
class UserService {
User register(String email, String password) { ... }
Session login(String email, String password) { ... }
void resetPassword(String email) { ... }
void uploadAvatar(User user, byte[] image) { ... }
byte[] resizeImage(byte[] image, int size) { ... }
void sendNewsletter(List<User> users) { ... }
String exportPersonalData(User user) { ... }
}Each group has a different reason to change: security, images, marketing and privacy law.
Different people ask for those changes. So split it along those lines: an Authentication
class, an AvatarStore, a Newsletter and a PersonalDataExport.
Name each group by its reason to change, and you’ve named the new classes. A bonus: the security-sensitive code now lives in one small class that’s easy to review.
Large class is often confused with two neighbors.
| Long Method | Large Class | Divergent Change | |
|---|---|---|---|
| What’s too big | one method | one class | (a symptom over time) |
| Too many… | steps | responsibilities | reasons to change |
| Main fix | Extract Method | Extract Class | split by reason (Extract Class) |
So size is a symptom; responsibilities are the cause. Count jobs, not lines.
Is every big class a problem? No.
class TicketingFacade {
private final BoxOffice boxOffice;
private final ConcertMailer mailer;
private final Poster poster;
void sell(String buyer) { boxOffice.sell(buyer); }
void remind() { mailer.sendReminders(); }
String poster() { return poster.render(); }
}So the real question isn’t how big it is. It’s whether it changes for one reason.
A large class tries to do too much. Spot it by groups of fields, islands of methods, vague names, many reasons to change, and heavy tests. Fix it with Extract Class, then move the behavior next to its data. Use Extract Subclass for fields only some objects need, and Extract Interface to separate the clients.
Don’t make every question go to Dave. Split by reason to change. One class, one job.