Code smell detection

From FerroxLabs/murage · View interactive version

Code smell detection is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level code smell detection implementation: clean-code and refactoring decision frameworks, production-ready patterns, and concrete templates for code smell detection workflows. Use when the user asks about code smell detection, code smell detection configuration, or clean-code best pra

How to use this skill

Skill file

Code Smell Detection

When to Use

Use this skill when:

Do NOT use this skill when:


Process

Step 1: Establish the Audit Scope and Smell Taxonomy

Before running any tool or reviewing any code, define the scope and the set of smells you are looking for. This prevents wasted effort and unfocused output.

Step 2: Select and Configure Static Analysis Tooling

Map the confirmed language and smell categories to concrete tools. Configure thresholds, not just enable defaults.

Step 3: Run Baseline Analysis and Collect Metrics

Execute the selected tools against the scoped codebase and record raw output without any filtering. You need the unfiltered baseline before triage.

Step 4: Triage and Prioritize Violations

Raw tool output is noisy. Triage reduces hundreds of violations to a manageable, prioritized list by combining severity, fixability, and risk.

Step 5: Implement Targeted Refactorings

For each prioritized smell, apply the canonical refactoring. Document the mapping between smell and fix.

Step 6: Integrate Smell Detection into CI/CD

Detection without enforcement creates a broken window effect. Quality gates must be automated.

Step 7: Establish Team Conventions and Living Documentation

Automated tools cannot catch every smell. Human pattern recognition in code review must be calibrated.


Output Format

When delivering smell analysis results, use the following structure:

## Code Smell Audit Report

**Project / Scope:** [module name, file range, or "full repository"]
**Language:** [language + runtime version]
**Analysis Date:** [date]
**Tools Used:** [list of tools + versions]
**Lines of Code Analyzed:** [LOC]

---

### Executive Summary

| Metric                          | Value          | Status     |
|---------------------------------|----------------|------------|
| Total Violations Found          | [N]            | [🔴/🟡/🟢] |
| Smell Density (violations/KLOC) | [N]            | [🔴/🟡/🟢] |
| Files Above Complexity Ceiling  | [N] of [total] | [🔴/🟡/🟢] |
| Dead Code Instances             | [N]            | [🔴/🟡/🟢] |
| Duplicate Code Blocks           | [N]            | [🔴/🟡/🟢] |

Status thresholds: 🟢 = within target, 🟡 = approaching limit, 🔴 = exceeds limit

---

### Smell Distribution by Category

| Category            | Count | % of Total | Trend vs. Last Audit |
|---------------------|-------|------------|----------------------|
| Bloaters            | [N]   | [%]        | [↑ / ↓ / →]         |
| OO Abusers          | [N]   | [%]        | [↑ / ↓ / →]         |
| Change Preventers   | [N]   | [%]        | [↑ / ↓ / →]         |
| Dispensables        | [N]   | [%]        | [↑ / ↓ / →]         |
| Couplers            | [N]   | [%]        | [↑ / ↓ / →]         |

---

### Hotspot Files (Churn × Complexity Matrix)

| File Path               | Complexity Score | Commits (90d) | Primary Smells              | Priority |
|-------------------------|------------------|---------------|-----------------------------|----------|
| [path/to/file.ext]      | [CC score]       | [N]           | [smell names]               | P1       |
| [path/to/file.ext]      | [CC score]       | [N]           | [smell names]               | P2       |

---

### Prioritized Violation List

#### P1 -- Fix Immediately

**[Smell Name] in [File:LineRange]**
- **Pattern Detected:** [Brief description of the specific instance]
- **Why It Matters:** [Specific risk -- regression likelihood, onboarding friction, etc.]
- **Recommended Refactoring:** [Specific move -- Extract Method, Extract Class, etc.]
- **Estimated Effort:** [S / M / L] ([hours estimate])
- **Before Sketch:**
  ```[language]
  [illustrative before code snippet]
  ```
- **After Sketch:**
  ```[language]
  [illustrative after code snippet]
  ```

#### P2 -- Fix in Next Sprint

[Same structure as P1, repeated per violation group]

#### P3 -- Fix Opportunistically

[List format acceptable here: file, smell, refactoring, effort]

---

### CI Configuration Recommendations

Recommended threshold configuration for [tool name]

[tool-specific YAML or config block with actual values filled in]


---

### Refactoring Roadmap

| Sprint | Target Files        | Smells Addressed              | Expected Debt Reduction |
|--------|---------------------|-------------------------------|------------------------|
| 1      | [file list]         | [smell names]                 | [hours]                |
| 2      | [file list]         | [smell names]                 | [hours]                |
| 3      | [file list]         | [smell names]                 | [hours]                |

---

### Suppression Register

| File | Line | Smell | Justification | Approved By | Expires |
|------|------|-------|---------------|-------------|---------|
| [path] | [N] | [name] | [reason] | [name] | [date or "never"] |

Rules

  1. Never equate line count alone with quality. A 50-line method composed of a single, well-named level of abstraction may be cleaner than a 10-line method with 4 nested conditionals and 3 levels of abstraction mixing. Always evaluate cyclomatic complexity and cognitive complexity alongside raw line count. Cognitive complexity (as defined by SonarSource) is a better proxy for human readability than cyclomatic complexity.
  1. Treat duplicate code across service boundaries differently than within a service. Within a single bounded context, duplicate code is a clear smell requiring extraction. Across microservices or independently deployable modules, shared libraries create coupling that may be worse than the duplication. The rule: tolerate duplication across deployment boundaries; eliminate it ruthlessly within them.
  1. Never suppress a smell without a dated justification comment. Suppressions that outlive their justification are worse than the original smell because they actively hide a known problem. Add an expiration date to every suppression -- six months is a reasonable default. Review suppressions in the monthly audit.
  1. Do not apply Extract Method purely to hit line-count thresholds. Methods extracted only to satisfy a linter with no semantic meaning (names like doPartOne, helperMethod2) are worse than the long method they replaced. Each extracted method must have a name that communicates a complete intent to a reader who has never seen the code.
  1. A class with high Afferent Coupling (many classes depend on it) requires more caution than a class with high Efferent Coupling when refactoring. High Ca means changes propagate outward to many dependents -- any refactoring requires a broader test suite validation. High Ce (class depends on many others) indicates Feature Envy or inappropriate intimacy but is safer to refactor because the blast radius is contained.
  1. Never run smell detection only once. A single audit produces a snapshot. The critical data is the trend: is smell density increasing, plateauing, or decreasing quarter over quarter? Configure tooling so every CI run produces a comparable metric that feeds a time-series view.
  1. Distinguish between smells in production code, test code, and generated code. Test code has different smell tolerances -- long test methods that set up complex scenarios may be acceptable if they maximize readability. Generated code (ORM models, protobuf stubs, GraphQL types) should be excluded entirely from smell analysis because developers cannot directly fix violations there.
  1. The Refused Bequest smell is frequently a sign that the inheritance hierarchy is wrong, not that the subclass needs more methods. Before adding behavior to the subclass to "satisfy" the smell detector, evaluate whether composition should replace inheritance entirely. Inheritance should model strict IS-A relationships; if a subclass only uses 30% of its parent's interface, the relationship is almost certainly not IS-A.
  1. Do not mistake high cyclomatic complexity for inherently bad code in all domains. Parsing logic, state machines, business rule engines, and configuration interpreters legitimately have high branching. For these modules, raise the threshold (e.g., 20 instead of 10), document the exception in the suppression register, and ensure the high-complexity code has exhaustive unit test coverage instead.
  1. Never use smell detection output as a performance review metric for individual developers. Violation counts assigned to authors by git blame create perverse incentives -- developers will suppress violations instead of fixing them, or avoid touching high-debt areas to keep their numbers clean. Smells are an aggregate team quality metric, never an individual accountability tool.

Edge Cases

Legacy Codebases with Thousands of Pre-existing Violations

When a codebase returns 10,000+ violations on the first analysis run, do not attempt to configure a CI gate that blocks on any existing violation -- it will block every PR indefinitely. Instead, apply the ratchet pattern:

Smells in Performance-Critical Inner Loops

A method that is called millions of times per second may legitimately inline logic that would normally be extracted. For example, avoiding virtual dispatch (Replace Conditional with Polymorphism) in a hot path is sometimes justified. The rule:

Monorepo with Inconsistent Smell Standards Across Teams

In a monorepo where 6 teams share a repository but have autonomy over their modules, smell standards will naturally diverge. Handle this by:

Dynamically Generated or Metaprogramming-Heavy Code

Languages like Ruby, Python, and JavaScript allow metaprogramming patterns (dynamic method definition, __getattr__, method_missing, decorators that wrap behavior) that generate apparent dead code or feature envy that is not real. Static analysis tools will flag these patterns incorrectly.

Smell Detection in a Polyglot Microservices Architecture

When each service uses a different language, a unified smell standard is difficult to enforce because thresholds are language-specific. Avoid the mistake of applying Java's 10-method complexity ceiling to Go or Ruby. Instead:

Smells Introduced by Framework Conventions

Some frameworks require patterns that look like code smells but are idiomatic. Django views can be long because they handle form validation, authentication, and response rendering in one place. Spring Boot configuration classes often have high Efferent Coupling by design. React components can have many props (parameter list smell). Address this by:

Refactoring Creates New Smells

A common failure mode: a developer extracts a large class into four smaller classes but introduces a Message Chain or Middle Man in the process. Each new class just delegates to the next.


Example

Input: "We have a Python 3.11 Django/REST API monolith with about 45,000 lines of code. Our team of 5 backend engineers is shipping features slowly because every change seems to break something unrelated. We don't have any automated smell detection set up yet. What should we do?"


Output:

Code Smell Audit Report

Project / Scope: Django REST API Monolith -- full repository

Language: Python 3.11

Analysis Date: [current date]

Tools Recommended: Pylint 3.x, Radon 6.x, Vulture 2.x, flake8 + flake8-cognitive-complexity, SonarCloud (free tier for open source or $10/dev/month)

Lines of Code: ~45,000


Diagnosis

The symptom -- "every change breaks something unrelated" -- is a textbook signature of two specific smell categories:

  1. Shotgun Surgery (Change Preventer): A single logical change requires edits in many unrelated files. This happens when a concept is represented in too many places simultaneously.
  2. Inappropriate Intimacy / Feature Envy (Couplers): Classes are excessively entangled with each other's internals, so changing one class's internal state propagates breakage to classes that should not care.

These smells often co-occur in Django codebases that started as simple CRUD apps and grew without refactoring the model layer. The Django ORM encourages models to become God Objects -- the User model, for example, accumulates authentication logic, profile logic, preference storage, billing relationships, and audit trail management over time because each developer adds their feature to the closest model.


Immediate Setup: Install and Configure Detection Tools

Step 1 -- Install tools:

pip install pylint radon vulture flake8 flake8-cognitive-complexity
pip install pylint-django  # critical for Django-aware Pylint

Step 2 -- Create .pylintrc with Django-appropriate thresholds:

[MASTER]
load-plugins=pylint_django
django-settings-module=myproject.settings

[DESIGN]
max-args=5
max-attributes=8
max-bool-expr=5
max-branches=12
max-locals=15
max-parents=5
max-public-methods=20
max-returns=6
max-statements=50
min-public-methods=2

[FORMAT]
max-line-length=119
max-module-lines=400

[SIMILARITIES]
min-similarity-lines=6
ignore-comments=yes
ignore-docstrings=yes

Step 3 -- Run the baseline audit:

# Cyclomatic complexity per function -- flag anything C rank (11-15) or above
radon cc ./myproject -s -a -n C

# Maintainability index -- flag anything below MI 20
radon mi ./myproject -s -n B

# Dead code detection
vulture ./myproject --min-confidence 80 --exclude "*/migrations/*,*/settings*"

# Pylint design violations only
pylint myproject --disable=all --enable=design -r y

# Cognitive complexity -- flag above 15
flake8 myproject --max-cognitive-complexity=15 --select=CCR001

Executive Summary (Projected from symptoms described)

In a 45,000-line Django monolith of this age without automated detection, expect the following on first run:

| Metric | Likely Finding | Target State |

|---------------------------------|--------------------|--------------------|

| Total Pylint Design Violations | 300--800 | <200 |

| Smell Density (violations/KLOC) | 7--18/KLOC | <8/KLOC |

| Methods with Cyclomatic CC > 10 | 40--100 methods | <15 methods |

| Dead Code Instances | 50--150 | 0 in active modules |

| Radon MI below 20 (unreadable) | 5--20 files | 0 files |


Hotspot Identification: The Churn × Complexity Matrix

Run this immediately -- it will identify your top 5 files responsible for most of your breakage:

# Get top 20 most-changed files in last 90 days
git log --since="90 days ago" --format=format: --name-only \
  | grep "\.py$" | sort | uniq -c | sort -rg | head -20

Cross-reference with Radon output. Files appearing in both lists are your P1 targets. In a Django monolith, these will almost certainly be:


The Primary Smell to Fix: God Object in Django Models

Django's models.py convention encourages developers to add business logic directly to model classes. Over 2--3 years of active development, a User or Order model becomes a 600-line class with 35+ methods spanning authentication, billing, notifications, and reporting. This is the most common source of "every change breaks something unrelated" in Django codebases.

Detection:

# Find model classes with more than 20 methods
radon raw ./myproject/*/models.py -s
pylint myproject --disable=all --enable=R0904  # too-many-public-methods

Illustrative Before (God Object -- models.py):

class User(AbstractUser):
    # ... 40+ fields ...

    def get_full_name(self): ...
    def update_profile(self, data): ...
    def send_welcome_email(self): ...  # should not be here
    def charge_subscription(self, plan): ...  # should not be here
    def calculate_invoice_total(self): ...  # should not be here
    def generate_pdf_invoice(self): ...  # should not be here
    def log_login_event(self, ip_address): ...  # should not be here
    def check_feature_flag(self, flag_name): ...  # should not be here
    # ... 20 more methods ...

Refactoring: Extract Service Classes (Domain Services pattern)

Apply Extract Class repeatedly, grouping by Single Responsibility:

# models.py -- User model retains ONLY persistence concerns
class User(AbstractUser):
    # Fields only -- no business logic beyond property accessors
    subscription_plan = models.CharField(...)
    profile_completed_at = models.DateTimeField(null=True)

    @property
    def is_subscribed(self):
        return self.subscription_plan is not None


# services/billing.py -- billing responsibility extracted
class BillingService:
    def __init__(self, user: User):
        self.user = user

    def charge_subscription(self, plan: str) -> PaymentResult:
        ...

    def calculate_invoice_total(self) -> Decimal:
        ...


# services/notifications.py -- notification responsibility extracted
class UserNotificationService:
    def __init__(self, user: User):
        self.user = user

    def send_welcome_email(self) -> None:
        ...


# services/audit.py -- audit responsibility extracted
class UserAuditService:
    def record_login(self, user: User, ip_address: str) -> None:
        ...

This extraction eliminates the God Object, reduces coupling (billing tests no longer require a full User object with all fields populated), and makes Shotgun Surgery visible -- when billing logic changes, only BillingService needs to change.


CI Quality Gate Configuration

Add to your CI pipeline (GitHub Actions example):

# .github/workflows/quality.yml
name: Code Quality Gate

on: [pull_request]

jobs:
  smell-detection:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # needed for git log churn analysis

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install analysis tools
        run: pip install pylint pylint-django radon vulture flake8 flake8-cognitive-complexity

      - name: Cyclomatic complexity gate (fail on new CC > 15)
        run: |
          radon cc ./myproject -s -n D --json > cc_report.json
          python scripts/check_new_violations.py cc_report.json  # compare vs baseline

      - name: Dead code gate (fail on any new dead code)
        run: |
          vulture ./myproject --min-confidence 80 \
            --exclude "*/migrations/*" \
            --make-whitelist > vulture_whitelist.py || true
          vulture ./myproject --min-confidence 80 \
            --exclude "*/migrations/*"

      - name: Cognitive complexity gate (fail on new violations > 15)
        run: |
          flake8 myproject \
            --max-cognitive-complexity=15 \
            --select=CCR001 \
            --count

90-Day Refactoring Roadmap

| Sprint (2 weeks) | Focus | Primary Smells Addressed | Expected Improvement |

|------------------|-------------------------------------------------|---------------------------------------|---------------------------------------------------|

| Sprint 1 | Top 3 hotspot files from churn/complexity matrix | God Object, Long Method | Reduces most common breakage source |

| Sprint 2 | Extract service layer for top 2 domain areas | Shotgun Surgery, Feature Envy | Changes to billing stop touching auth code |

| Sprint 3 | Dead code removal + duplicate code elimination | Dispensables, Duplicate Code | Reduces cognitive load and test surface area |

| Sprint 4 | CI gate implementation + team catalog creation | Process (prevention) | Prevents new debt accumulation |

| Sprint 5--6 | Remaining P2 violations from initial audit | Bloaters, remaining Couplers | Smell density drops below 8/KLOC target |


Suppression Register (initial entries for known Django framework smells)

| File | Line | Smell | Justification | Approved By | Expires |

|----------------------|-------|-----------------------|------------------------------------------------------------|-------------|-------------|

| */views.py | n/a | too-many-public-methods (>20) | Django class-based views use method-per-HTTP-verb convention | Team lead | Review Q3 |

| */admin.py | n/a | Long Method | Django admin get_queryset and save_model are framework entry points | Team lead | Review Q3 |

| */migrations/*.py | n/a | All smells | Auto-generated -- not maintained by hand | Team lead | Never |


Key Insight for This Codebase

The "every change breaks something unrelated" symptom will not be fully resolved by smell detection alone -- but addressing God Objects and Shotgun Surgery in the top 5 hotspot files will likely reduce your cross-feature regression rate by 50--70% within 6 weeks, based on the pattern this symptom typically represents. The most important action is the Churn × Complexity matrix: identify those files today, in the next 30 minutes, before writing a single line of refactoring code. Every other improvement follows from fixing what you find there.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.