Large Class

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.

Ask Dave

Three questions, can I get a refund, did the reminder go out, and where is the fire exit, all go to Dave, who runs the box office, the mailing list, the posters and the building. Three questions, can I get a refund, did the reminder go out, and where is the fire exit, all go to Dave, who runs the box office, the mailing list, the posters and the building.
Every question goes to Dave.

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.

What it looks like

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.

ConcertManager splits into four groups: venue with venueName, venueAddress, venueCapacity and directions; tickets with ticketPrice, ticketsSold, sellTicket, refund, isSoldOut and revenue; mail with mailHost, mailSender, sendReminders and sendNewsletter; posters with posterTemplate and renderPoster. ConcertManager splits into four groups: venue with venueName, venueAddress, venueCapacity and directions; tickets with ticketPrice, ticketsSold, sellTicket, refund, isSoldOut and revenue; mail with mailHost, mailSender, sendReminders and sendNewsletter; posters with posterTemplate and renderPoster.
Four in-trays on one desk.

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.

Why it hurts

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.

Three unrelated pull requests, add refunds, a new mail provider and a poster redesign, all edit ConcertManager.java, which leads to a merge conflict. Three unrelated pull requests, add refunds, a new mail provider and a poster redesign, all edit ConcertManager.java, which leads to a merge conflict.
Unrelated changes, one file.

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 to spot it

How do you spot a large class? Look for five signals.

  1. Groups of fields. Fields that share a prefix, like venue…, ticket… and mail…, or that are always used together.

  2. Methods that only use some of the fields. Draw a grid of which method uses which field, and you’ll see islands:

    Methodvenue fieldsticket fieldsmail fieldsposter 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.)

  3. A vague name. Manager, Processor, Helper, Utils. Or a description that needs the word and: “manages concerts and tickets and mail and posters”.

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

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

The key insight: one reason to change

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.

Before: one ConcertManager holds the venue, tickets, mail and posters. After: Concert coordinates Venue, BoxOffice, ConcertMailer and Poster, and BoxOffice reads the Venue's capacity. Before: one ConcertManager holds the venue, tickets, mail and posters. After: Concert coordinates Venue, BoxOffice, ConcertMailer and Poster, and BoxOffice reads the Venue's capacity.
One desk with four in-trays (top) versus a small team (bottom).

One class, one job. Split by reason to change.

What stays behind

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);
    }
}
Class diagram: Concert holds a Venue, a BoxOffice and a ConcertMailer. BoxOffice holds the Venue and offers sell, isSoldOut and revenue. ConcertMailer offers sendConfirmation, sendReminders and sendNewsletter. Class diagram: Concert holds a Venue, a BoxOffice and a ConcertMailer. BoxOffice holds the Venue and offers sell, isSoldOut and revenue. ConcertMailer offers sendConfirmation, sendReminders and sendNewsletter.

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.

The revenue method left behind in Concert reads BoxOffice's sold count and price, so Move Method sends it to BoxOffice, where it reads its own fields. The revenue method left behind in Concert reads BoxOffice's sold count and price, so Move Method sends it to BoxOffice, where it reads its own fields.
Extract the data, then move the behavior home.

Fields only some objects use: Extract Subclass

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();
    }
}
Class diagram: Festival extends Concert. Concert keeps basePrice and ticketPrice; Festival adds stages, campingSpots and overrides ticketPrice. Class diagram: Festival extends Concert. Concert keeps basePrice and ticketPrice; Festival adds stages, campingSpots and overrides ticketPrice.

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.

Different clients, different slices: Extract Interface

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;
}
Class diagram: ConcertManager implements the TicketSales interface with sellTicket and isSoldOut. CheckoutPage depends only on TicketSales, while Reports and Marketing still use ConcertManager directly. Class diagram: ConcertManager implements the TicketSales interface with sellTicket and isSoldOut. CheckoutPage depends only on TicketSales, while Reports and Marketing still use ConcertManager directly.

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

A second example: the UserService

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.

UserService splits by reason to change: security goes to Authentication with register, login and resetPassword; images go to AvatarStore with uploadAvatar and resizeImage; marketing goes to Newsletter with sendNewsletter; privacy law goes to PersonalDataExport with exportPersonalData. UserService splits by reason to change: security goes to Authentication with register, login and resetPassword; images go to AvatarStore with uploadAvatar and resizeImage; marketing goes to Newsletter with sendNewsletter; privacy law goes to PersonalDataExport with exportPersonalData.
Name the reason to change, and you've named the class.

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.

Commonly confused: Long Method and Divergent Change

Large class is often confused with two neighbors.

  • Long Method is one method with too many steps. Large class is one class with too many jobs. They often show up together, and extracting methods can make a class even bigger. That’s when Extract Class comes next.
  • Divergent Change is how a large class feels over time: one class, edited again and again, for many different reasons (see the Shotgun Surgery lesson, where it’s the mirror image).
Long MethodLarge ClassDivergent Change
What’s too bigone methodone class(a symptom over time)
Too many…stepsresponsibilitiesreasons to change
Main fixExtract MethodExtract Classsplit by reason (Extract Class)

So size is a symptom; responsibilities are the cause. Count jobs, not lines.

When it’s acceptable

Is every big class a problem? No.

  • Cohesive data holders. A data holder can have many fields if they all describe one thing. A flight booking might have twelve fields (reference, passenger, flight number, from, to, departure, arrival, seat, cabin, fare, bags, status) and still have one job.
  • Facades. A facade is wide on purpose. It gives a simple front door to a whole subsystem, but every method is a one-line delegation. Wide, but thin. Like a receptionist who points you to the right office.
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(); }
}
  • Generated code (parsers, protocol stubs) is regenerated, not edited, so its size costs little.
Decision flowchart: is a big class a smell? If its fields all describe one thing, it is a cohesive data holder, fine. If every method only delegates, it is a facade, fine. If it holds logic for several reasons to change, it is a Large Class: extract classes along the seams. Decision flowchart: is a big class a smell? If its fields all describe one thing, it is a cohesive data holder, fine. If every method only delegates, it is a facade, fine. If it holds logic for several reasons to change, it is a Large Class: extract classes along the seams.
The question isn't how big it is; it's how many reasons it has to change.

So the real question isn’t how big it is. It’s whether it changes for one reason.

Recap

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.

Recap chain: group the fields by prefix and usage; Extract Class for each group; move leftover behavior next to its data; the result is one class, one job. Recap chain: group the fields by prefix and usage; Extract Class for each group; move leftover behavior next to its data; the result is one class, one job.
Split by reason to change.
  • Large Class: a class trying to do too much (a God class).
  • It hurts because nobody can hold it in their head, unrelated changes collide, tests need the whole world, and nothing can be reused alone.
  • Spot it: field groups, method islands, vague names, many reasons to change, heavy tests.
  • Fix it: Extract Class (then Move Method for leftovers), Extract Subclass for variant-only fields, Extract Interface to separate clients.
  • Don’t confuse it with Long Method (too many steps) or Divergent Change (its symptom over time).
  • Leave it when it’s a cohesive data holder, a thin facade, or generated code.

Don’t make every question go to Dave. Split by reason to change. One class, one job.

Further reading

  • Martin Fowler, Refactoring: Improving the Design of Existing Code (2nd ed.), chapter 3 (“Large Class”, “Divergent Change”) and the Extract Class, Extract Subclass, Extract Superclass and Move Function refactorings.
  • Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices: the Single Responsibility and Interface Segregation principles.
  • Refactoring.Guru: Large Class
  • Related lessons: Long Method, Feature Envy, Shotgun Surgery, Refused Bequest, Command Pattern (one more way to pull jobs out of a big class).