# Large ClassEvery 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.

{{< lesson-video youtube="jeh7SG1EzP8" title="Large Class" >}}

## Ask Dave

```mermaid {alt="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." caption="Every question goes to Dave."}
flowchart LR
  Q1["Can I get a refund?"] --> D["Dave"]
  Q2["Did the reminder<br/>go out?"] --> D
  Q3["Where's the<br/>fire exit?"] --> D
  D --- J1["box office"]
  D --- J2["mailing list"]
  D --- J3["posters"]
  D --- J4["the building"]
  class D bad
  class Q1,Q2,Q3 hl
  class J1 c4
  class J2 c5
  class J3 c6
  class J4 c1
```

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:

```java
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.

```mermaid {alt="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." caption="Four in-trays on one desk."}
flowchart LR
  CM["ConcertManager"] --> V["venue<br/>venueName, venueAddress,<br/>venueCapacity, directions()"]
  CM --> T["tickets<br/>ticketPrice, ticketsSold,<br/>sellTicket(), refund(),<br/>isSoldOut(), revenue()"]
  CM --> M["mail<br/>mailHost, mailSender,<br/>sendReminders(),<br/>sendNewsletter()"]
  CM --> P["posters<br/>posterTemplate,<br/>renderPoster()"]
  class CM bad
  class V c1
  class T c4
  class M c5
  class P c6
```

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.

```mermaid {alt="Three unrelated pull requests, add refunds, a new mail provider and a poster redesign, all edit ConcertManager.java, which leads to a merge conflict." caption="Unrelated changes, one file."}
flowchart LR
  A["PR: add refunds"] --> F["ConcertManager.java"]
  B["PR: new mail provider"] --> F
  C["PR: poster redesign"] --> F
  F --> X["merge conflict"]
  class A c4
  class B c5
  class C c6
  class F warn
  class X bad
```

**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:

```java
@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:

   | 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.)
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](/code-smells/divergent-change/), also covered in the
   [Shotgun Surgery lesson](/code-smells/shotgun-surgery/#the-classic-opposite-divergent-change).
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:

```java
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.

```mermaid {alt="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." caption="One desk with four in-trays (top) versus a small team (bottom)."}
flowchart TB
  subgraph BEFORE["Before: one class, four jobs"]
    direction LR
    G["ConcertManager<br/>venue + tickets +<br/>mail + posters"]
  end
  subgraph AFTER["After: Extract Class"]
    direction LR
    C["Concert<br/>coordinates"] --> V["Venue"]
    C --> B["BoxOffice"]
    C --> M["ConcertMailer"]
    C --> P["Poster"]
    B -.-> V
  end
  BEFORE ~~~ AFTER
  class G bad
  class C good
  class V c1
  class B c4
  class M c5
  class P c6
```

> **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:

```java
class Concert {
    private final Venue venue;
    private final BoxOffice boxOffice;
    private final ConcertMailer mailer;

    void sellTicket(String buyer) {
        boxOffice.sell(buyer);
        mailer.sendConfirmation(buyer);
    }
}
```

```mermaid {alt="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."}
classDiagram
  class Concert {
    -Venue venue
    -BoxOffice boxOffice
    -ConcertMailer mailer
    +sellTicket(String buyer)
  }
  class Venue {
    <<record>>
    +String name
    +String address
    +int capacity
  }
  class BoxOffice {
    -double price
    -int sold
    +sell(String buyer)
    +isSoldOut() boolean
    +revenue() double
  }
  class ConcertMailer {
    +sendConfirmation(String buyer)
    +sendReminders()
    +sendNewsletter()
  }
  Concert o--> Venue
  Concert o--> BoxOffice
  Concert o--> ConcertMailer
  BoxOffice o--> Venue
```

But watch for leftovers. This revenue method stayed behind in the concert. It only reads the
box office's numbers:

```java
// left behind in Concert: it only reads BoxOffice's data
double revenue() {
    return boxOffice.getSold() * boxOffice.getPrice();
}
```

That's [Feature Envy](/code-smells/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.

```mermaid {alt="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." caption="Extract the data, then move the behavior home."}
flowchart LR
  L["Concert.revenue()<br/>reads boxOffice.getSold()<br/>and getPrice()"] -->|Move Method| R["BoxOffice.revenue()<br/>sold * price"]
  class L bad
  class R c4
```

## 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:

```java
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:

```java
class Festival extends Concert {
    private List<String> stages;
    private int campingSpots;

    @Override
    double ticketPrice() {
        return super.ticketPrice() + campingFee();
    }
}
```

```mermaid {alt="Class diagram: Festival extends Concert. Concert keeps basePrice and ticketPrice; Festival adds stages, campingSpots and overrides ticketPrice."}
classDiagram
  class Concert {
    -double basePrice
    +ticketPrice() double
  }
  class Festival {
    -List~String~ stages
    -int campingSpots
    +ticketPrice() double
  }
  Concert <|-- Festival
```

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](/code-smells/refused-bequest/) 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:

```java
interface TicketSales {
    void sellTicket(String buyer);
    boolean isSoldOut();
}

class CheckoutPage {
    private final TicketSales sales;
}
```

```mermaid {alt="Class diagram: ConcertManager implements the TicketSales interface with sellTicket and isSoldOut. CheckoutPage depends only on TicketSales, while Reports and Marketing still use ConcertManager directly."}
classDiagram
  class TicketSales {
    <<interface>>
    +sellTicket(String buyer)
    +isSoldOut() boolean
  }
  class ConcertManager {
    +sellTicket(String buyer)
    +isSoldOut() boolean
    +revenue() double
    +sendNewsletter()
  }
  TicketSales <|.. ConcertManager
  CheckoutPage --> TicketSales
  Reports --> ConcertManager
  Marketing --> ConcertManager
```

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:

```java
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`.

```mermaid {alt="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." caption="Name the reason to change, and you've named the class."}
flowchart TD
  U["UserService"] -->|security| A["Authentication<br/>register, login,<br/>resetPassword"]
  U -->|images| S["AvatarStore<br/>uploadAvatar,<br/>resizeImage"]
  U -->|marketing| N["Newsletter<br/>sendNewsletter"]
  U -->|privacy law| E["PersonalDataExport<br/>exportPersonalData"]
  class U bad
  class A c4
  class S c1
  class N c5
  class E c6
```

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**](/code-smells/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](/code-smells/shotgun-surgery/), where it's the mirror image).

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

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

```java
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.

```mermaid {alt="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." caption="The question isn't how big it is; it's how many reasons it has to change."}
flowchart TD
  Q{"Does it change<br/>for one reason?"} -->|"yes: fields describe<br/>one thing"| D["Data holder<br/>fine"]
  Q -->|"yes: methods only<br/>delegate"| F["Facade<br/>fine"]
  Q -->|"no: logic for<br/>several reasons"| L["Large Class:<br/>Extract Class<br/>along the seams"]
  class Q warn
  class D,F good
  class L bad
```

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.

```mermaid {alt="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." caption="Split by reason to change."}
flowchart LR
  A["Group the fields<br/>prefixes, islands"] --> B["Extract Class<br/>per group"]
  B --> C["Move behavior<br/>next to its data"]
  C --> D["One class,<br/>one job"]
  class A bad
  class B,C hl
  class D good
```

- **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](/code-smells/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](https://refactoring.guru/smells/large-class)
- Related lessons: [Long Method](/code-smells/long-method/),
  [Feature Envy](/code-smells/feature-envy/),
  [Shotgun Surgery](/code-smells/shotgun-surgery/),
  [Refused Bequest](/code-smells/refused-bequest/),
  [Command Pattern](/patterns/command-pattern/) (one more way to pull jobs out of a big class).
