# Lazy ClassA recipe app with a one-line formatter, a one-number holder and an empty subclass. Learn to spot classes that don't earn their keep and fold them in without losing good small classes.

A recipe app has just had a big refactoring spree. A new teammate opens the project to learn how an
ingredient works, and opens three files: an ingredient name formatter with one method that trims a
string and makes it lower case, a quantity holder that wraps a single number and gives it a getter,
and a special ingredient that extends ingredient and adds nothing at all. Three files opened, and
nothing learned. That's a smell called **Lazy Class**: a class that does too little to justify its
existence.

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.

{{< lesson-video youtube="P54vp84Qho4" title="Lazy Class" >}}

## Three files, nothing inside

Here is the teammate's first morning as a picture, and what it looks like after the fix.

```mermaid {alt="Before and after folding. Before: the Ingredient class depends on IngredientNameFormatter and QuantityHolder, and SpecialIngredient extends it, so a reader opens four files. After: only the Ingredient class remains." caption="Before and after."}
flowchart LR
  subgraph Before
    direction TB
    B1["Ingredient"] --> B2["IngredientNameFormatter<br/>one line"]
    B1 --> B3["QuantityHolder<br/>one number"]
    B4["SpecialIngredient<br/>adds nothing"] -->|extends| B1
  end
  subgraph After
    direction TB
    A1["Ingredient<br/>one file, one idea"]
  end
  Before ~~~ After
  class B2,B3,B4 bad
  class A1 good
```

## The spoon drawer

Picture a kitchen drawer that holds a single spoon. Every time you want that spoon, you pull the
drawer, look, and push it shut. It costs a pull every time, and it takes up a slot in the cabinet. A
guest has to open it just to learn there's nothing else inside. The fix is easy: put the spoon in the
cutlery drawer, and take the empty drawer away.

In code, the drawer is a class. A class costs something every time anyone **reads** it, **names**
it, **tests** it or **searches** for it. So a class has to earn its upkeep. When it doesn't, we fold
it into something bigger.

## What it looks like

Here are the three classes. The formatter has one method, and the method has one line.

```java
class IngredientNameFormatter {
    String format(String name) {
        return name.trim().toLowerCase();
    }
}
```

The quantity holder keeps a double, sets it in the constructor, and returns it with a getter.

```java
class QuantityHolder {
    private final double amount;

    QuantityHolder(double amount) {
        this.amount = amount;
    }

    double getAmount() {
        return amount;
    }
}
```

And special ingredient extends ingredient, passes its arguments up, and stops there.

```java
class SpecialIngredient extends Ingredient {
    SpecialIngredient(String name, double amount) {
        super(name, amount);
    }
}
```

Honestly, each one felt sensible when it was written. Formatting names is a real job. A quantity
might need units one day. A special ingredient sounds like a special kind. A class born with a reason
is easy to keep. The trouble starts when the reason never shows up.

(`Recipe` and imports are left out of the snippets; all names are invented examples.)

## Why it hurts

So what do these small classes cost? **Reading** comes first. To follow the `label` method, a
teammate opens three files.

```java
class Ingredient {
    private final String name;
    private final QuantityHolder quantity;

    Ingredient(String name, double amount) {
        this.name = name;
        this.quantity = new QuantityHolder(amount);
    }

    String label() {
        String clean = new IngredientNameFormatter().format(name);
        return clean + " x" + quantity.getAmount();
    }
}
```

**Naming** costs too. Is it a formatter, a holder, a helper? Every extra class is another word the
team has to remember. **Testing** is third: the formatter wants its own test class for one line, and
so does the getter, if your coverage rules insist. And **finding**: search for `Ingredient`, and the
results fill up with files that say nothing. None of these costs is big. But they never stop, and
everyone pays them, every time.

## How to spot it

- **It does almost nothing.** A constructor, a getter and nothing else is a strong hint.
- **One caller.** A class used from one place is often a method in disguise.
- **A subclass that adds nothing.** No new fields, no new methods, no overrides.
- **Where did it come from?** The Code Smells Reference names two causes: a feature that never
  arrived, and a class that shrank after other refactorings moved its work away.

Notice that none of the tells says *small*. Size alone proves nothing.

## The key insight: a class must earn its keep

A class pays rent in reading, naming, testing and finding. What can a class earn? A rule that it
guards. A name for an idea the domain really has. Or a seam you need for a test. If the earnings
cover the rent, keep the class. If they don't, fold it into the class that uses it.

> **If a class doesn't earn its keep, fold it in.**

## Fold one: Inline Class

The first fold is called **Inline Class**. Move everything from the lazy class into the class that
uses it, then delete the lazy one. Start with the formatter: its one line moves into the `label`
method, and the formatter class goes. Now the holder: its number becomes a field on `Ingredient`,
and the getter call becomes the field itself.

```java
class Ingredient {
    private final String name;
    private final double amount;

    Ingredient(String name, double amount) {
        this.name = name;
        this.amount = amount;
    }

    String label() {
        String clean = name.trim().toLowerCase();
        return clean + " x" + amount;
    }
}
```

Notice the direction: everything moves **toward the user of the class**, never away from it. Fowler's
catalog names this move Inline Class, and refactoring.guru lists it for this smell. Now one file
reads, names and tests the whole idea.

## Fold two: Collapse Hierarchy

The second fold is **Collapse Hierarchy**, the one the course page lists. It merges a subclass that
barely differs from its superclass. `SpecialIngredient` adds no fields, no methods and no overrides,
so every use of it can become a plain `Ingredient`.

```java
Ingredient saffron = new SpecialIngredient("saffron", 2);
```

```java
Ingredient saffron = new Ingredient("saffron", 2);
```

Then delete the subclass. This time the direction is **up**: the subclass folds into its superclass.
It can go the other way too: if a superclass only exists to head a hierarchy with one child, the
superclass folds **down** into the child. Now replay the first scene: the new teammate opens one file,
`Ingredient`, and the `label` method reads top to bottom.

```mermaid {alt="Class diagram after folding. Recipe holds many Ingredient objects. Ingredient has a name, an amount and a label method. The formatter, holder and special subclass no longer exist." caption="After both folds."}
classDiagram
  direction LR
  class Recipe {
    ingredientNames()
  }
  class Ingredient {
    String name
    double amount
    label()
  }
  Recipe o--> Ingredient
```

## A second example: a class that shrank

Here's a second case. A shopping list builder used to merge duplicate items and sort them. Those steps
moved into `Recipe` during earlier refactorings, and what's left is one method that asks the recipe
for its names.

```java
class ShoppingListBuilder {
    List<String> build(Recipe recipe) {
        return recipe.ingredientNames();
    }
}
```

That's the course page's second cause: a class that shrank. Nothing is wrong with the code, but the
class no longer has a job. Inline it: the callers ask the recipe for its names directly, and the
builder is gone.

```java
List<String> items = new ShoppingListBuilder().build(recipe);
```

```java
List<String> items = recipe.ingredientNames();
```

If a class only forwards calls, that's closer to [Middle Man](/code-smells/middle-man/).
Different name, same question: does it earn its keep?

## Misconception: small classes are bad

"Small classes are always bad." No. The smell is a class with **no reason to exist**, not a small
class. Compare the quantity holder with a quantity. Both are tiny. The holder only stores a number.
The quantity rejects negative amounts.

```java
record Quantity(double amount, String unit) {
    Quantity {
        if (amount < 0) {
            throw new IllegalArgumentException("negative amount");
        }
    }
}
```

That rule is its reason to exist: every quantity in the app is valid, because only one place checks.
It's a value object, like the ones in [Primitive Obsession](/code-smells/primitive-obsession/):
a bare number gets a name and rules. A tiny class can also name an idea the domain really uses, like
servings. If people say the word out loud, the class is earning its place.

## When to leave it

So when do you leave a small class alone?

- **When it guards a rule**, like `Quantity` does.
- **When it's a seam you need for testing right now**, so a test can swap the real thing for a fake.
- **When it's about to grow**, because of a planned feature with a date. The Code Smells Reference
  says to leave those alone.

But be honest. A feature someone might want one day is not a plan. That's
[Speculative Generality](/code-smells/speculative-generality/), building for a future that never
came. Lazy class is what's left behind when speculation fails; speculative generality is the habit
that makes it. No date on the calendar? Fold the class in. If the feature does arrive, you can extract
it again.

```mermaid {alt="Decision flow. Does the class do almost nothing? If no, leave it. If yes, does it guard a rule or name a domain idea? If yes, keep it. If no, is a test using it as a seam today, or is a feature scheduled? If yes, keep it and note why. If no, fold it in with Inline Class or Collapse Hierarchy." caption="When to fold."}
flowchart TD
  Q1{"does almost nothing?"} -->|no| L["leave it"]
  Q1 -->|yes| Q2{"guards a rule or<br/>names a domain idea?"}
  Q2 -->|yes| K["keep it"]
  Q2 -->|no| Q3{"a test seam today,<br/>or a feature with a date?"}
  Q3 -->|yes| N["keep it, note why"]
  Q3 -->|no| X["fold it in<br/>Inline Class or<br/>Collapse Hierarchy"]
  class X good
  class L,K,N muted
```

## Recap

A lazy class does too little to justify its upkeep. Spot it by what it does, who calls it, and where
it came from. Fix it with Inline Class, or Collapse Hierarchy. Small is fine when a class guards a
rule, names an idea, or has a scheduled future.

```mermaid {alt="Recap chain: a lazy class does too little for its upkeep, spot it by what, who and why, then fold it in with Inline Class or Collapse Hierarchy." caption="Earn your keep."}
flowchart LR
  A["does too little<br/>for its upkeep"] --> B["spot it:<br/>what, who, why"] --> C["Inline Class,<br/>Collapse Hierarchy"]
  class C good
```

Checklist:

- Does the class do almost nothing: a constructor, a getter, one forwarding call?
- Is it used from one place, or is it a subclass that adds nothing?
- Does it guard a rule, name a domain idea, or serve as a test seam today?
- Is a feature that needs it actually scheduled?
- If none of those, fold it in, and move toward the class that uses it.

> **If a class doesn't earn its keep, fold it in.**

## Further reading

- Code Smells Reference: [Lazy Class](https://refactoring-assistant.github.io/dispensables/lazy-class).
- Martin Fowler and Kent Beck, *Refactoring* (2nd ed., 2018), chapter 3, where this smell is called
  "Lazy Element".
- Refactoring catalog: [Inline Class](https://refactoring.com/catalog/inlineClass.html),
  [Collapse Hierarchy](https://refactoring.com/catalog/collapseHierarchy.html).
- refactoring.guru: [Lazy Class](https://refactoring.guru/smells/lazy-class).
