# CommentsA payroll comment says overtime is paid at 1.5x while the code says 1.25. Learn to replace what-comments with code that explains itself, and to keep the why-comments that are worth keeping.

Here's the pay method from a payroll system. Every few lines, a comment explains the next step.
One comment says overtime is paid at one and a half times. But the code right under it multiplies
by 1.25. Last year, someone changed the code and forgot the comment. So which one is right? You
can't tell by reading. That's a smell called **Comments**: notes that explain unclear code.

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="mk5oLxQ1afI" title="Comments" >}}

## Which one is right?

Here's the method. Look at the overtime comment and the line under it:

```java
double pay(Employee e) {
    // hours worked this period, never negative
    double hours = e.hours();
    // regular pay: up to 40 hours at the base rate
    double pay = Math.min(hours, 40) * e.rate();
    // check overtime: over 40 hours, 1.5x
    if (hours > 40) {
        pay += (hours - 40) * e.rate() * 1.25;
    }
    // subtract unpaid leave
    pay -= e.unpaidDays() * 8 * e.rate();
    // never pay less than zero
    if (pay < 0) {
        pay = 0;
    }
    // round to whole cents
    return Math.round(pay * 100) / 100.0;
}
```

The comment says 1.5x. The code says `1.25`. (The rates, hours and ticket numbers in this article are
made-up example values; `Employee` stands for a small class with `hours()`, `rate()` and
`unpaidDays()`.)

## The sign on the door

Think of a door with a pull handle, and a sign taped on that says "PUSH". Every visitor reads the
sign, tries to push, and bumps into the door. The sign isn't helping. It's covering for a bad door.
The fix isn't a bigger sign. It's a door shaped so that nobody needs to read anything.

A comment that explains what code does is that sign. **If the code needs a sign, fix the code.**

A sign that says *why* the door is locked is different, say "fire exit". That tells you something
the door can't.

## What it looks like

Let's read it fairly. Someone took the time to explain every step, and that's kind. The method
goes step by step: regular pay, overtime, unpaid leave, a floor at zero, and rounding. A newcomer can
follow it without reading any code. And that's the trouble: the comments are doing the code's job.
The [course reference page](https://refactoring-assistant.github.io/dispensables/comments) puts it
this way: if the code needs a comment to be understood, that is a hint that the code isn't clear
enough on its own. And in a very long method, comments feel like the only map you have, which is
why they spread (see [Long Method](/code-smells/long-method/)).

## Why it hurts

**Nothing checks a comment.** The compiler ignores it, and so do your tests.

**Code changes, and comments stay put.** That's how the overtime comment ended up saying one and a half
while the code says one and a quarter. Now every reader has to choose. Trust the comment, and you
misquote the policy. Trust the code, and you wonder whether it's a bug.

**Comments double the reading.** You read the comment, then the code, then decide whether they
agree.

**A what-comment is a deodorant.** It covers the smell and doesn't remove it.
(refactoring.guru uses the same image: comments written with good intentions can mask code that
could be improved.)

```mermaid {alt="Before and after. Before: the pay method holds the code and six comments side by side; the comment says 1.5x while the code says 1.25, and nothing checks the difference. After: the pay method calls named steps regularPay, overtimePay and roundToCents and uses the named constant OVERTIME_MULTIPLIER, with one comment left for the reason, so there is nothing to contradict." caption="The meaning moves from comments into names."}
flowchart LR
  subgraph after["After: the code says it"]
    direction TB
    P2["pay()"] --> R2["regularPay()"]
    P2 --> O2["overtimePay()"]
    O2 --> K2["OVERTIME_MULTIPLIER<br/>one why-comment"]
    P2 --> C2["roundToCents()"]
  end
  subgraph before["Before: comments carry the meaning"]
    direction TB
    P1["pay()"] --> M1["comment says 1.5x"]
    P1 --> D1["code says 1.25"]
    M1 -.->|"nothing checks"| D1
  end
  class P1,M1,D1 bad
  class P2,R2,O2,K2,C2 good
```

## How to spot it

1. **A comment that restates the next line**, like "add the tax, then subtract the discount".
2. **A comment above a block that works like a heading.** "Check overtime." "Subtract unpaid leave."
   Each one is a method waiting for a name.
3. **A comment that explains what a variable means.** If a name needs a footnote, change the name.
4. **A comment that states a rule nothing checks**, like "always between 0 and 100".
5. **Code that has been commented out.** That's dead code: version control remembers it, so delete
   it. ([Dead Code](/code-smells/dead-code/) argues the same.)

Every one of those comments explains *what*. Keep that word in mind. Its partner, *why*, comes next.

## The key insight: what versus why

A comment can answer two questions: what does this code do, and why is it this way?

A **what comment** is a failure of the code. The name, the structure or the types should already say
it. A **why comment** is a gift. It holds a business reason, a workaround, or a surprise that no code
can express. So when you want to write a what comment, try this first: change the code until the
comment isn't needed.

> **Don't explain the code. Let the code explain itself, and keep the why.**

```mermaid {alt="Decision flow for a comment. Does it say what the code does? If yes, make the code say it with Extract Method, Rename, Extract Variable or an assertion, then delete the comment. If it says why, keep it: a business reason, a workaround, a legal header, public API docs or a ticketed TODO." caption="Is this comment a what or a why?"}
flowchart TD
  A{"does the comment say<br/>what the code does?"}
  A -->|yes| B["make the code say it:<br/>Extract Method, Rename,<br/>Extract Variable, Assertion"]
  B --> D["delete the comment"]
  A -->|"no: it says why"| K["keep it:<br/>business reason, workaround,<br/>legal header, API docs,<br/>ticketed TODO"]
  class B,D good
  class K hl
```

## The fix: make the code say it

Start with **Extract Method**. Take the commented block, move it into a method, and use the comment
as the name. Overtime becomes `overtimePay`. Regular pay and rounding get names too. Unpaid leave
becomes a variable called `unpaidLeave`. That last move is **Extract Variable** (Fowler's older name
is Introduce Explaining Variable).

The magic numbers get names too: forty hours is `REGULAR_HOURS`, and the multiplier is a constant, so
the number lives in one place. And the comment about hours never being negative becomes an assertion,
**Introduce Assertion**:

```java
class Payroll {
    private static final int REGULAR_HOURS = 40;
    private static final int HOURS_PER_DAY = 8;
    // Reduced by the pay policy change (ticket HR-1187).
    private static final double OVERTIME_MULTIPLIER = 1.25;

    double pay(Employee e) {
        assert e.hours() >= 0 : "hours are never negative";
        double unpaidLeave = e.unpaidDays() * HOURS_PER_DAY * e.rate();
        double total = regularPay(e) + overtimePay(e) - unpaidLeave;
        return roundToCents(Math.max(total, 0));
    }
```

The methods behind the names:

```java
    private double regularPay(Employee e) {
        return Math.min(e.hours(), REGULAR_HOURS) * e.rate();
    }

    private double overtimePay(Employee e) {
        double extraHours = Math.max(e.hours() - REGULAR_HOURS, 0);
        return extraHours * e.rate() * OVERTIME_MULTIPLIER;
    }

    private double roundToCents(double amount) {
        return Math.round(amount * 100) / 100.0;
    }
}
```

Assertions are switched on with `-ea` (they are off by default), and they suit assumptions in
non-public methods. Don't use them to check the arguments of public methods; there, throw an
exception, as the second example shows ([Oracle's assertion guide](https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html)).

Take small steps. Extract one comment at a time, and run the tests after each one. The course page
lists Extract Method (for a commented block) and Introduce Assertion (for a stated assumption);
refactoring.guru adds Extract Variable (for a complex expression) and Rename Method (for a method that
still needs a comment).

```mermaid {alt="Class diagram of the refactored design. Payroll has constants REGULAR_HOURS, HOURS_PER_DAY and OVERTIME_MULTIPLIER, a pay method, and private methods regularPay, overtimePay and roundToCents. Payroll depends on Employee for hours, rate and unpaid days." caption="Each comment became a name."}
classDiagram
  class Payroll {
    -int REGULAR_HOURS
    -int HOURS_PER_DAY
    -double OVERTIME_MULTIPLIER
    +pay(Employee) double
    -regularPay(Employee) double
    -overtimePay(Employee) double
    -roundToCents(double) double
  }
  Payroll ..> Employee : hours, rate, unpaidDays
```

## Replay, and the comment that stays

Now replay the question: which multiplier is right? There's one place to look, and the code uses
what it finds there.

But why did it drop from the old rate? The code can't say that. So one comment stays, with its ticket:
the line above `OVERTIME_MULTIPLIER`. Notice it repeats no number. A why comment that never repeats the
code can't contradict it. And it points at a ticket, so anyone can open it and judge whether the
reason still holds.

## A second example: names and rules

A smaller case. A discount stores a value called `p`, and a comment says it's the percent off,
between 0 and 100:

```java
class Discount {
    private final double p; // percent off, between 0 and 100

    Discount(double p) {
        this.p = p;
    }

    // price after the discount
    double calc(double price) {
        return price - price * p / 100;
    }
}
```

That comment does two jobs. It's a footnote for a bad name, and it states a rule that nothing checks.
Rename `p` to `percentOff`, and the footnote has nothing left to say. Rename `calc` to `priceAfter`,
and its comment goes too. In Fowler's catalog those are **Rename Variable** and **Change Function
Declaration** (also called Rename Method). The rule becomes a real check:

```java
class Discount {
    private final double percentOff;

    Discount(double percentOff) {
        if (percentOff < 0 || percentOff > 100) {
            throw new IllegalArgumentException(
                    "percentOff must be 0 to 100");
        }
        this.percentOff = percentOff;
    }

    double priceAfter(double price) {
        return price - price * percentOff / 100;
    }
}
```

It's an exception here, not an assertion, because this constructor is public and assertions can be
switched off. (The course page's own example for Introduce Assertion is a constructor comment that
says RGB values must be in range while nothing enforces it. Either way, the stated rule becomes
something the program checks.)

## The comments worth keeping

Not every comment is a smell. Keep four kinds:

- a **why comment**: a business rule or a workaround;
- a **legal header**: it says who owns the file;
- **Javadoc on a public method**: it tells callers what to expect without reading the body (the course
  page leaves documentation comments out of the smell);
- a **TODO tied to a ticket**: it can be searched and closed. A bare TODO is only a wish.

```java
// Copyright (c) 2026 Acme Payroll. All rights reserved.

/** Pays one employee for one period. The result is never negative. */
public double pay(Employee e) {
    // Finance rounds down here, by rule (ticket FIN-212).
    double paid = Math.floor(e.gross() * 100) / 100;
    // TODO(HR-1190): add bonus days once the rules are approved.
    return Math.max(paid, 0);
}
```

(The ticket numbers are made-up. The four-kinds list is our own judgment, consistent with the course
page's when-to-ignore list.)

## Myths, and when to leave it

**Myth: good code has no comments.** Not quite. The aim is no *what* comments. *Why* comments are
valuable. A codebase with no why comments loses its reasons, and then the next person removes your
workaround, because it looks wrong.

So leave a comment alone when it is:

- **public API docs**, because callers depend on them;
- a **regulatory or legal note**, because someone will audit it;
- a **link to the bug or the spec** behind odd code. Odd code deserves its reason;
- an explanation of a **complex algorithm**, after attempts to simplify it have failed (the course page
  lists this and why-comments as the cases to ignore).

One exception: commented-out code. Delete it. That's what [Dead Code](/code-smells/dead-code/) is.

## Recap

A comment that says what the code does is a deodorant for unclear code. Spot it by restated lines,
headings, footnotes and unchecked rules. Fix it with Extract Method, Rename, Extract Variable and
Introduce Assertion. A long method is where what-comments gather, so fix
[that](/code-smells/long-method/) first. And keep the why.

```mermaid {alt="Recap chain: what-comments cover unclear code; spot restated lines, headings, footnotes and unchecked rules; fix with Extract Method, Rename, Extract Variable and Introduce Assertion; keep the why." caption="Don't explain the code. Let the code explain itself, and keep the why."}
flowchart LR
  A["what-comments<br/>cover unclear code"] --> B["spot: restated lines,<br/>headings, footnotes"] --> C["fix: Extract Method, Rename,<br/>Extract Variable, Assertion"] --> D["keep the why"]
  class C good
```

Checklist:

- Does the comment restate the line below it, or act as a heading for a block?
- Does a name need a footnote?
- Does the comment state a rule nothing checks?
- Could a method, a variable, a rename or an assertion say it instead?
- If it explains why (a reason, a workaround, a legal note, a public API), leave it.

> **Don't explain the code. Let the code explain itself, and keep the why.**

## Further reading

- [Comments](https://refactoring-assistant.github.io/dispensables/comments), the course's Code Smells Reference.
- [Comments](https://refactoring.guru/smells/comments) on refactoring.guru.
- Fowler's refactoring catalog: [Extract Function](https://refactoring.com/catalog/extractFunction.html) (Extract Method),
  [Extract Variable](https://refactoring.com/catalog/extractVariable.html),
  [Change Function Declaration](https://refactoring.com/catalog/changeFunctionDeclaration.html),
  [Rename Variable](https://refactoring.com/catalog/renameVariable.html),
  [Introduce Assertion](https://refactoring.com/catalog/introduceAssertion.html).
- Oracle: [Programming With Assertions](https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html).
