Code Smells: What They Are, 12 Examples and How to Find Them

Raghav Chamadiya11 min read
On this page

A code smell is a surface sign in source code that usually points to a deeper design problem, such as a function that is too long, a class that does too much or logic copied in several places. The code still works. The smell says it will be harder to change than it should be.

This guide covers what a code smell is, how it differs from a bug and from technical debt, twelve common smells with examples, the smells that only git history reveals, the rule of three, how to find smells automatically, and which to fix first.

What is a code smell?

Martin Fowler's definition is the standard one: "a code smell is a surface indication that usually corresponds to a deeper problem in the system." Kent Beck coined the term while helping Fowler with Refactoring, and the 1999 book gave it a chapter, "Bad Smells in Code", that lists each smell next to the refactorings that remove it (Fowler's bliki).

Two words in that definition matter. Surface means a smell is quick to spot: you can see a 400-line function without understanding it. Usually means a smell is a reason to look, not a verdict. Fowler is explicit that some long methods are just fine. A smell is a question about the design, and sometimes the answer is that the design is right.

Smells are usually grouped into five families, a grouping that comes from Mika Mäntylä's taxonomy and is now common in teaching material:

FamilyWhat goes wrongSmells in it
BloatersCode grows too large to hold in your headLong method, large class, long parameter list, primitive obsession, data clumps
Object-orientation abusersLanguage features used against their grainSwitch statements on type, refused bequest, temporary field
Change preventersOne change forces many editsDivergent change, shotgun surgery, parallel inheritance
DispensablesCode that adds nothingDuplicated code, dead code, speculative generality, lazy class, comments that explain bad code
CouplersClasses too entangled with each otherFeature envy, inappropriate intimacy, message chains, middle man

Scroll the table sideways to see every column.

Code smell vs bug vs technical debt

A bug is wrong behavior, a code smell is a sign of poor structure, and technical debt is the accumulated cost of that structure. They are related but not the same thing, and mixing them up leads to the wrong fix.

BugCode smellTechnical debt
What it isCode that produces the wrong resultA visible pattern that suggests a design problemThe extra cost every future change pays because of the design
Does the code work?NoYesYes
Found byTests, users, monitoringReading the code, linters, analysis toolsSlower delivery, recurring bugs in the same places
Fixed byChanging behaviorRefactoring, keeping behavior the samePaying it down over time, usually by refactoring hotspots

Scroll the table sideways to see every column.

Smells are how debt becomes visible in code. Our guide to what technical debt is covers the cost side; the glossary entry on code smells has the short definition.

12 common code smells with examples

These twelve cover most of what reviewers flag in practice. Each has a one-line test for spotting it and the refactoring that usually removes it.

1. Long method

A function that does several jobs in a row: validate, compute, persist, notify. You know it when you need comments to mark its sections.

python
def place_order(cart, user):
    # validate
    if not cart.items: raise ValueError("empty")
    # price
    total = sum(i.price * i.qty for i in cart.items)
    if user.is_member: total *= 0.9
    # persist
    order = db.insert("orders", user_id=user.id, total=total)
    # notify
    mailer.send(user.email, f"Order {order.id} confirmed")
    return order

Fix: Extract Method for each commented block. The longest function we found in a 10k+ star repository on repowise.dev is a 6,967-line self-test in PowerToys; the longest functions in popular repos breaks down which long functions are worth splitting.

2. Large class (god class)

A class with dozens of fields and methods that serve unrelated purposes, often named Manager, Service, Utils or after the app itself. Most of the codebase imports it, and every feature edits it.

Fix: Extract Class along the groups of fields and methods that are used together.

3. Duplicated code

The same logic in two or more places, often with small differences that drift apart over time. A bug fixed in one copy stays in the others.

Fix: Extract Method or Extract Function into a shared helper, once you have seen it three times (see the rule of three below).

4. Long parameter list

typescript
function createUser(name: string, email: string, street: string, city: string,
                    zip: string, country: string, isAdmin: boolean, sendWelcome: boolean) { ... }

Eight positional arguments, two of them booleans that are easy to swap. Fix: Introduce Parameter Object (an Address type) and replace boolean flags with separate functions or an options object.

5. Feature envy

A method that uses another object's data more than its own:

python
def shipping_cost(order):
    return order.customer.address.zone.base_rate * order.customer.address.zone.multiplier

Fix: Move Method to the class whose data it uses, here Zone.cost().

6. Shotgun surgery

One logical change requires small edits in many files. Adding a new payment method means touching the enum, the validator, three switch statements, the serializer and the admin form.

Fix: Move the scattered pieces into one module that owns the concept. Shotgun surgery is hard to see in any single file; it shows up in history (next section).

7. Divergent change

The mirror image: one file changes for many unrelated reasons. The same class is edited for database changes, UI changes and pricing rules.

Fix: Extract Class so each reason to change lives in its own unit.

8. Primitive obsession

Using strings and integers for domain ideas: an email as str, money as float, a status as "pending".

python
def refund(amount: float, currency: str, status: str): ...

Fix: Replace Primitive with Object (Money, Email, an OrderStatus enum). Validation moves into one place.

9. Dead code

Functions, exports and whole files that nothing calls. They still cost reading time, show up in search, and get updated in refactors for no reason. Across 190 popular open-source repositories we analysed (November 2026), the median repo had 16.2 dead-code findings per 100 production files, and 89% had at least one production file nothing imports.

Fix: Delete it, after checking dynamic entry points. How to find dead code in your repository has the commands per language.

10. Speculative generality

Abstractions built for a future that never came: an interface with one implementation, a plugin system with one plugin, parameters nobody passes.

Fix: Inline Class, Collapse Hierarchy, remove the unused parameters. Add the abstraction back when a second case actually arrives.

11. Deep nesting

javascript
if (user) {
  if (user.active) {
    for (const order of user.orders) {
      if (order.open) {
        if (order.items.length > 0) {
          ship(order);
        }
      }
    }
  }
}

Five levels deep to reach one line of work. Fix: Replace Nested Conditional with Guard Clauses (return early) and extract the loop body into a function.

12. Data clumps

The same three or four values always travel together: start_date, end_date, timezone, or host, port, user, password.

Fix: Group them into one object. Data clumps are usually the first step toward a long parameter list.

Smells you can only see in history

Some smells are invisible in a snapshot of the code and obvious in its git history. A linter or a reviewer reading one file cannot see that two files always change together, or that one file is edited for every feature. The same blind spot is why self-documenting code cannot explain why a design looks the way it does.

  • Shotgun surgery appears as co-change: a set of files that land in the same commits again and again. If orders/models.py, orders/serializers.py and admin/orders.py share most of their commits, one concept is spread across three files.
  • Divergent change appears as churn with mixed intent: one file in a large share of commits, each touching a different concern.
  • Hidden coupling is co-change between files with no import between them. Nothing in the code says they are related; the history says they are. Our guide to hidden coupling and co-change detection shows how to find these pairs with plain git log.

You can get a rough list yourself:

bash
# files changed most often in the last 6 months: candidates for divergent change
git log --since="6 months ago" --name-only --pretty=format: | sort | uniq -c | sort -rn | head -20

The rule of three in refactoring

The rule of three says: the first time you write something, just write it; the second time, wince at the duplication and write it anyway; the third time, refactor. Fowler credits it to Don Roberts in Refactoring, and it is the standard answer to "when should I remove duplicated code?"

The reason is that two copies are not enough to know what the shared abstraction should be. With three, the common part and the varying part are clear, and the helper you extract will fit all of them. Extract too early and you build speculative generality, the tenth smell on the list.

How to find code smells automatically

Linters catch the single-function smells, analysis platforms catch more across files, and history-aware tools catch the ones that only show in git.

Tool typeSmells it findsExamples
LintersLong functions, too many parameters, deep nesting, high complexity, unused variablesESLint (max-lines-per-function, max-params, max-depth, complexity), Pylint (too-many-arguments, too-many-branches), RuboCop metrics cops
Static analysis platformsThe above plus duplication across files and cognitive complexitySonarQube, PMD (including its copy-paste detector, CPD)
History-aware analysisShotgun surgery, divergent change, hidden coupling, smells ranked by churn and bug fixesrepowise, CodeScene

Scroll the table sideways to see every column.

What does SonarQube call a code smell? SonarQube reports code smells as its maintainability issues, next to bugs (reliability) and vulnerabilities (security). Each comes from a language rule, such as "Cognitive Complexity of functions should not be too high", and carries an estimated time to fix. Our guide to what SonarQube is covers how it groups findings and gates pull requests.

The limit of a flat list is volume. In 160 popular repositories (200,744 production files), 23.3% of files contain a function above McCabe's threshold of 10. Turn on a complexity rule in an existing codebase and you get thousands of findings with no order. Code complexity metrics explains what those thresholds measure.

How repowise finds and ranks code smells

repowise detects the common smells from the parse tree and the git history, and ranks them by how much they cost you to keep. It runs 59 deterministic detectors during repowise init and repowise update, with no LLM key and no network, and scores every file from 1 to 10.

Smellrepowise detector family
Long method, high complexitySize and complexity: long or high-CCN functions
God class, deep nesting, complex conditionsStructural complexity
Primitive obsessionSize and complexity
Duplicated codeDuplication: cloned blocks
Shotgun surgery, divergent changeChange history: co-change scatter, churn, change entropy
Dead codeThe dead-code layer: unreachable files, unused exports, unused packages

Scroll the table sideways to see every column.

The score shows how strongly these shapes go with poor health. Across those 200,744 files, files whose most complex function stays at 10 or below have a median health of 10.0; files whose worst function is above 50 have a median of 3.09, and 59.5% of them score below 4. (Complexity is an input to the score, so this shows how the score treats complexity, not independent proof of defects.)

bash
repowise init
repowise health                         # Fix first: the ranked list, each with a first edit and tests to run
repowise health --refactoring-targets   # refactoring plans: Extract Method, Extract Class, Split File and more

History decides the order: a complex function in a file that changes every week ranks above the same function in a file nobody touches. Each Fix first item names the refactoring, the first step and the tests to run, and asks for a characterization test when none reaches the code. See it on a real repository in the FastAPI code health report, and read more on the code health, refactoring and dead code feature pages.

Which code smell should you fix first?

Fix the smell in the file that changes most and breaks most, not the worst-looking smell in the codebase. A smell costs time only when someone has to read or change the code around it.

  1. Start with hotspots. Rank files by churn over the last few months; the top 10% usually take most of the change. In the median repo of the 195 we analysed, 10% of files absorb 68% of all line churn over 90 days. Git hotspot analysis shows the commands.
  2. Within hotspots, favor files with recent bug fixes. In the same cohort, the least-healthy 20% of files hold 60% of files that needed a fix in the last 180 days.
  3. Pick local, mechanical fixes first. Extract Method on a long function is low risk; moving a god class across modules is not.
  4. Add a test before you touch untested code. A characterization test pins today's behavior so the refactoring can be checked.
  5. Leave smells in dormant code alone. A long function nobody has changed in two years is a smell with no cost. To stop new smells arriving, write the limits into your coding standards and enforce them in CI.

FAQ

What is a smell in programming?
A smell, or code smell, is a pattern in source code that suggests a deeper design problem, such as a very long function, a class that does too much, or duplicated logic. The code still works. The smell signals that it will be harder to read and change, and points to a refactoring that would help.
What is the rule of three in refactoring?
It says to tolerate duplication twice and refactor on the third occurrence. With three copies, the shared part and the varying part are clear, so the extracted helper fits every case. Martin Fowler credits the rule to Don Roberts in his book Refactoring.
Are code smells bugs?
No. A bug is code that behaves incorrectly; a code smell is code that works but is structured in a way that makes change harder. Smells do go with bugs: complex, frequently changed code is where fixes concentrate, so a smell in a busy file is a good place to look for the next defect.
What does SonarQube call a code smell?
SonarQube uses "code smell" for its maintainability issues, alongside bugs for reliability and vulnerabilities for security. Each smell is a language rule, such as a function that is too complex or a duplicated block, with an estimated time to fix that feeds its technical debt figure.
How do you detect code smells?
Linters such as ESLint, Pylint and RuboCop detect single-function smells through rules on length, parameters, nesting and complexity. Platforms such as SonarQube and PMD add duplication and cognitive complexity. Smells like shotgun surgery need git history, which tools such as repowise read to find files that always change together.
What are the most common code smells?
The most common are long method, large class, duplicated code, long parameter list, feature envy, shotgun surgery, primitive obsession, dead code and deep nesting. Long methods and duplication are the two reviewers flag most, because they are easy to see and expensive to keep.