code quality

What Is a Code Smell? 12 Common Smells and Their Fixes

By Zest | Updated | 13 min read
A laptop on a desk with smoke drifting across a screen that reads Fix Code Smells

A code smell is a sign in working code that a deeper design problem may be underneath, like a function too long to follow or logic pasted in three places. Kent Beck coined the term while helping Martin Fowler write Refactoring (1999), which lists the common smells and a fix for each.

When a coding agent wrote the smelly code, Zest shows which session and model led to that pull request, and what it cost. Start freeGet started

Fowler’s own definition is “a surface indication that usually corresponds to a deeper problem in the system”, and he credits the term to Beck (Martin Fowler). The word “usually” matters: a smell tells you where to look, not that something is wrong. When something is wrong, the fix is a refactoring, a small change to the code’s structure that leaves its behavior alone.

What makes something a code smell

Fowler’s definition of a code smell hides two points. A smell is quick to spot, “sniffable” in his word: his example is a long method, and his nose twitches “if I see more than a dozen lines of java”. And a smell is not a verdict: “smells don’t always indicate a problem. Some long methods are just fine.”

Smells were Beck’s answer to a question the first edition of Refactoring had to settle: when to refactor. Fowler was visiting Beck in Zurich while writing it, and Beck had come up with describing the “when” in terms of smells. Fowler suspects Beck “was under the influence of the odors of his newborn daughter at the time” (Refactoring, 2nd edition, chapter 3). The two wrote the smells chapter together and refused to set thresholds: “In our experience, no set of metrics rivals informed human intuition.”

That makes smells easy to teach: they’re “easy for inexperienced people to spot”, Fowler notes, and some lead developers pick a “smell of the week” for the team to look for.

Code smell vs. bug

A bug is code that does the wrong thing. A smell is code that does the right thing in a way that makes the next change harder or riskier.

SonarQube, which reports both, sorts its rules by elimination: a rule about code an attacker could exploit is a vulnerability, one about security-sensitive code is a security hotspot, one about code that is “demonstrably wrong, or more likely wrong than not” is a bug, and anything else is a code smell (SonarQube docs).

Smells can turn into bugs. Duplicated code is the plainest case. In Fowler and Beck’s words, “If you need to change the duplicated code, you have to find and catch each duplication”, and the copy you miss is the bug.

Smells are also where technical debt shows up in code. SonarQube’s technical debt metric is defined as “A measure of effort to fix all code smells” (SonarQube metrics). For deciding which debt to pay down first, see how to reduce technical debt.

12 common code smells and how to fix them

The second edition of Refactoring (2018) lists 24 smells in chapter 3, each with the refactorings that usually clear it (chapter 3 on InformIT). Here are twelve, with the refactoring Fowler and Beck reach for first. The names are the second edition’s; older names you’ll still see elsewhere are in parentheses. Fowler’s online catalog describes each refactoring.

Smell What it looks like Usual refactoring
Mysterious Name A function, variable or class whose name doesn’t say what it does or how to use it Change Function Declaration, Rename Variable, Rename Field
Duplicated Code The same code structure in more than one place Extract Function; Slide Statements first if the copies differ slightly
Long Function (Long Method) A function you have to read top to bottom to learn what it does, often with comments marking its sections Extract Function; Decompose Conditional for big conditionals
Long Parameter List Many parameters, or a flag argument that switches behavior Introduce Parameter Object, Preserve Whole Object, Remove Flag Argument
Large Class A class with too many fields and too much code Extract Class
Data Clumps The same three or four values together, as fields and parameters, in many places Extract Class, Introduce Parameter Object
Primitive Obsession Money, ranges or phone numbers kept as plain numbers and strings Replace Primitive with Object
Repeated Switches (Switch Statements) The same switch or if/else cascade in several places Replace Conditional with Polymorphism
Feature Envy A function that uses another module’s data more than its own Move Function, after Extract Function on the envious part
Divergent Change One module you change for unrelated reasons, say for every new database and for every new financial instrument Split Phase, Move Function, Extract Class
Shotgun Surgery One change that needs small edits in many classes Move Function, Move Field, Combine Functions into Class
Speculative Generality Hooks and parameters for needs that never came, or code whose only callers are tests Collapse Hierarchy, Inline Function, Remove Dead Code

The other twelve are Global Data, Mutable Data, Loops, Lazy Element, Temporary Field, Message Chains, Middle Man, Insider Trading, Alternative Classes with Different Interfaces, Data Class, Refused Bequest and Comments. Comments make the list only as “a deodorant” over bad code; Fowler and Beck call comments themselves “a sweet smell”.

Four code smells, before and after

Each example shows a smell in TypeScript, then the same code after a refactoring. Every “after” does exactly what its “before” did; that’s what makes it a refactoring.

Long Function: turn the comments into functions

Fowler and Beck’s heuristic is “whenever we feel the need to comment something, we write a function instead.” This function needs three comments to be readable:

function invoiceTotal(invoice: Invoice): number {
  // add up the lines
  let subtotal = 0;
  for (const line of invoice.lines) {
    subtotal += line.unitPrice * line.quantity;
  }

  // members get 10% off orders over 100
  let discount = 0;
  if (invoice.customer.isMember && subtotal > 100) {
    discount = subtotal * 0.1;
  }

  // tax is charged on the discounted amount
  const tax = (subtotal - discount) * invoice.taxRate;

  return subtotal - discount + tax;
}

The first two comments become function names, the third a variable name, and the loop becomes a pipeline (Replace Loop with Pipeline):

function invoiceTotal(invoice: Invoice): number {
  const discounted = subtotal(invoice) - memberDiscount(invoice);
  return discounted + discounted * invoice.taxRate;
}

function subtotal(invoice: Invoice): number {
  return invoice.lines.reduce((sum, line) => sum + line.unitPrice * line.quantity, 0);
}

function memberDiscount(invoice: Invoice): number {
  const amount = subtotal(invoice);
  return invoice.customer.isMember && amount > 100 ? amount * 0.1 : 0;
}

The top function now reads as its own summary. memberDiscount computes the subtotal again instead of taking it as a parameter: that’s Replace Temp with Query, so temporary variables don’t get in the way of extracting.

Duplicated Code: one rule, one place

Two files work out a person’s display name the same way:

// billing/receipt.ts
const name = customer.displayName?.trim() || customer.email.split("@")[0];

// email/welcome.ts
const greeting = `Hi ${user.displayName?.trim() || user.email.split("@")[0]},`;

Nothing is broken yet. But when the rule changes, say to prefer a first name, someone has to find both copies. Extract the rule once and call it from both places:

// people/display-name.ts
export function displayName(person: { displayName?: string; email: string }): string {
  return person.displayName?.trim() || person.email.split("@")[0];
}

// billing/receipt.ts
const name = displayName(customer);

// email/welcome.ts
const greeting = `Hi ${displayName(user)},`;

Duplication is also the smell with the clearest trend data as AI writes more of the code; more on that below.

Data Clumps: give values that travel together a type

start and end go everywhere together, and each function repeats the same comparison:

function mergedPullRequests(prs: PullRequest[], start: Date, end: Date): PullRequest[] {
  return prs.filter((pr) => pr.mergedAt !== null && pr.mergedAt >= start && pr.mergedAt < end);
}

function sessionCost(sessions: Session[], start: Date, end: Date): number {
  return sessions
    .filter((s) => s.startedAt >= start && s.startedAt < end)
    .reduce((sum, s) => sum + s.costUsd, 0);
}

They are a range, so make them one object (Introduce Parameter Object):

class DateRange {
  constructor(
    readonly start: Date,
    readonly end: Date,
  ) {}

  contains(date: Date): boolean {
    return date >= this.start && date < this.end;
  }
}

function mergedPullRequests(prs: PullRequest[], range: DateRange): PullRequest[] {
  return prs.filter((pr) => pr.mergedAt !== null && range.contains(pr.mergedAt));
}

function sessionCost(sessions: Session[], range: DateRange): number {
  return sessions
    .filter((s) => range.contains(s.startedAt))
    .reduce((sum, s) => sum + s.costUsd, 0);
}

The comparison lives in one place, so the next function can’t use <= where the others use <. Fowler and Beck’s test for a clump: delete one of the values and ask whether the rest still make sense. If not, “you have an object that’s dying to be born.” A start without an end means nothing.

Repeated Switches: each case in one place

The same switch on the shipping method sits in two functions, and a new method means finding every one of them:

type ShippingMethod = "standard" | "express" | "overnight";

function shippingCost(method: ShippingMethod, weightKg: number): number {
  switch (method) {
    case "standard":
      return 5;
    case "express":
      return 10 + weightKg * 2;
    case "overnight":
      return 25 + weightKg * 4;
  }
}

function deliveryDays(method: ShippingMethod): number {
  switch (method) {
    case "standard":
      return 5;
    case "express":
      return 2;
    case "overnight":
      return 1;
  }
}

The first edition’s smell was called “switch statements”. The second edition narrowed it to switches that repeat, because “whenever you add a clause, you have to find all the switches and update them.” The fix is Replace Conditional with Polymorphism: each case becomes an object that carries its own behavior.

interface Shipping {
  cost(weightKg: number): number;
  days: number;
}

const SHIPPING: Record<ShippingMethod, Shipping> = {
  standard: { cost: () => 5, days: 5 },
  express: { cost: (kg) => 10 + kg * 2, days: 2 },
  overnight: { cost: (kg) => 25 + kg * 4, days: 1 },
};

const shippingCost = (method: ShippingMethod, weightKg: number) => SHIPPING[method].cost(weightKg);
const deliveryDays = (method: ShippingMethod) => SHIPPING[method].days;

A new shipping method is now one entry. Because SHIPPING is typed as Record<ShippingMethod, Shipping>, once you add the method to ShippingMethod the compiler rejects the code until that entry exists.

How to find code smells

In code review. Smells are quick to spot by definition, so look for them while you read a diff, and name the smell and the refactoring in your comment (“Feature Envy: move this into Customer?”). The author gets the problem and a fix in a few words. More on reviewing in code review good practices.

With a linter. A linter catches the smells you can count. ESLint has max-lines-per-function (default 50 lines; its docs say “Some people consider large functions a code smell”), max-params (default 3), complexity (default 20) and max-depth (default 4). None of the four is in ESLint’s recommended set, so you turn them on yourself. no-unused-vars, which is in it, flags unused variables, functions and parameters. Our linter guide covers setting one up.

With a static analyzer. SonarQube calls its maintainability issues code smells, by name; in its MQR mode the same issue type is called Maintainability (SonarQube glossary). It counts them across a project and on new code, and it finds duplicated blocks: in most languages, at least 100 duplicated tokens in a row spread over at least 10 lines (SonarQube metrics). For code smell rules Sonar targets zero false positives, “so that developers do not have to wonder if a fix is required.”

In your change history. Divergent Change and Shotgun Surgery don’t show up in any one file, so a linter can’t see them. They show up in history: one file that keeps changing for unrelated reasons, or the same group of files that changes together in commit after commit. When a feature touches six files, ask why.

Can you measure code smells?

Partly. Tools count the smells they can detect: SonarQube reports a code smell count and turns each issue into minutes of remediation effort, and ESLint reports every rule you turned on. Watch the trend on new code rather than the total. The count says nothing about Feature Envy, Divergent Change or a misleading name. To measure code quality more broadly, see how to measure code quality.

When not to fix a code smell

A smell is a reason to look, and sometimes the right call after looking is to leave it.

  • Nobody is changing the code. Fowler on technical debt: “If I have a terrible area of the code base, one that’s a nightmare to change, it’s not a problem if I don’t have to modify it” (Martin Fowler). Clean up code you’re about to change anyway, the habit often called the camp site rule: “always leave the code behind in a better state than you found it” (Opportunistic Refactoring).
  • The smell is faint. Of Refused Bequest, a subclass that uses little of what it inherits, Fowler and Beck write: “Nine times out of ten this smell is too faint to be worth cleaning.” They also exempt a data class that holds the result of one step.
  • There are no tests. A refactoring changes structure “without changing its observable behavior” (Martin Fowler), and only tests can tell you it didn’t. Fowler’s rule is to “only refactor when your tests are green.” On untested code, first write tests that pin down what it does today (unit testing best practices).
  • You’re in the middle of something else. One cleanup turns up the next, and Fowler warns of “a genuine danger of going down a rabbit hole”. Make a note and come back to it “the same day”, before you call the task done.
  • The fix changes behavior. Then it isn’t a refactoring. Ship the restructuring and the behavior change in separate pull requests, so a reviewer can check that the first changes nothing.

Code smells in AI-written code

Coding agents write code that passes its tests and still smells.

What the studies show

Two large studies, both by companies that sell code-quality tools, agree:

  • Most issues are smells. In a 2025 paper, researchers at Sonar, which makes SonarQube, ran it on Java written by five models for 4,442 coding assignments: Claude Sonnet 4, Claude 3.7 Sonnet, GPT-4o, Llama 3.2 90B and OpenCoder 8B. For every model, about 90–93% of the issues were code smells, 5–8% bugs and about 2% vulnerabilities. Dead, unused or redundant code was the largest smell category for three of the five, between 26% and 43% of their smells. How well a model did on the functional tests didn’t predict the quality of its code (Sabra, Schmitt and Tyler, 2025).
  • More duplication, less refactoring. GitClear, which sells engineering analytics, studied 623 million code changes from 2023 to 2026. Duplicated blocks, five or more repeated meaningful lines in a row, rose from 40.3 per million changed lines in 2023 to 73.0 so far in 2026, up 81%. Moved code, its marker for refactoring, fell from 21% of changed lines in 2022 to 3.8% so far in 2026, while copy/pasted lines rose from 9.4% in 2022 to 15.7% in the first half of 2026 (GitClear, 2026). GitClear measures all code, not only AI-written code, and ties the trend to the growing share of commits that AI writes.

The Sonar authors suggest a reason for the dead code: spotting it “can require a whole-project reference analysis”, and a model works within a limited context window. The same limit may also explain some of the duplication: an agent that never sees your existing helper writes a new one.

How to keep smells out of agent code

Three habits help:

  • Run the same checks on agent code as on yours, where the agent sees the output: in CI, or in a hook that runs the linter after each edit. Agents act on findings they’re shown. In our repositories, coding agents fixed 80% of the 2,273 findings from IonWarp, our sister product’s AI code reviewer, that they answered in the 30 days to October 4, 2026, declined 18% and handed 1.6% to a person (what 866 agent-written pull requests show).
  • Write the smells you care about into the agent’s instructions file (CLAUDE.md for Claude Code, AGENTS.md for Codex): search for an existing helper before writing one, delete code you replace, no unused parameters “for later”.
  • Ask for the refactor by name. An agent that got the tests to pass has finished the green step of red, green, refactor, not the refactor step. Ask it to look for duplication and unclear names in its own diff, tests still passing, before you review.

Zest is ours, and it doesn’t find code smells: it runs no analyzer, reviews no code and collects no code diffs. It records each engineer’s coding-agent sessions and links each one to the GitHub pull request it led to, so when a smelly pull request comes in you can see which agent, model and session produced it. For the smells themselves, use SonarQube or your linter.

Frequently asked questions

Who coined the term code smell?

Kent Beck, while Martin Fowler was writing the first edition of Refactoring, published in 1999. The two wrote the book’s smells chapter together.

How many code smells are there?

There is no fixed list. The second edition of Refactoring (2018) names 24. Refactoring.guru lists 23, some under older names such as Long Method, plus a few the second edition doesn’t have, such as Parallel Inheritance Hierarchies and Dead Code.

What are the five categories of code smells?

The five groups are the ones refactoring.guru uses: Bloaters (code grown too big, like Long Method and Large Class), Object-Orientation Abusers (such as Switch Statements and Refused Bequest), Change Preventers (Divergent Change, Shotgun Surgery), Dispensables (Duplicate Code, Dead Code, Speculative Generality) and Couplers (Feature Envy, Message Chains). Fowler and Beck’s chapter lists its smells without groups.

Can tools detect code smells automatically?

Some of them. Linters and analyzers find the countable ones: long functions, long parameter lists, deep nesting, duplicated blocks and unused code. Smells about where code belongs, like Feature Envy or Divergent Change, still need someone who knows the design.

What is the difference between a code smell and technical debt?

A code smell is a symptom you can see in the code. Technical debt is the extra effort the code costs you each time you change it. Many smells are debt, but not all debt is a smell: a half-finished migration or a manual release process smells of nothing in a single file.

Zest is AI coding analytics for engineering teams: it shows which coding agents, models and skills each engineer uses, what they cost, and which sessions end in merged pull requests. See how Zest works.