Skip to main content
ClaudeWave
Skill85 repo starsupdated 3mo ago

code-smell-detector

Identify and report code smells indicating poor design or maintainability issues in Python code, including duplicate code, magic numbers, hardcoded values, God classes, feature envy, inappropriate intimacy, data clumps, primitive obsession, and long parameter lists. Use when conducting code quality audits, preparing for refactoring, improving codebase maintainability, or performing design reviews. Produces markdown reports with severity ratings, locations, descriptions, and specific refactoring recommendations with before/after examples. Triggers when users ask to find code smells, identify design issues, suggest refactorings, improve code quality, or detect maintainability problems.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/code-smell-detector && cp -r /tmp/code-smell-detector/skills/code-smell-detector ~/.claude/skills/code-smell-detector
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# Code Smell Detector

## Overview

Identify code quality and design smells in Python codebases, then provide specific refactoring recommendations to improve maintainability and design.

## Workflow

### 1. Understand the Analysis Scope

Define what to analyze:

**Questions to ask:**
- What directory or files should be analyzed?
- Focus on quality smells, design smells, or both?
- Are there specific concerns (e.g., "this class is too complex")?
- Should test files be included?

**Determine scope:**
```bash
# Check project structure
ls -la

# Count Python files
find . -name "*.py" | wc -l

# Identify large files (potential smells)
find . -name "*.py" -exec wc -l {} + | sort -rn | head -10
```

### 2. Detect Code Smells

Use multiple detection strategies.

#### Strategy 1: Automated Detection

Use the bundled script for AST-based analysis:

```bash
# Scan entire project
python scripts/detect_smells.py /path/to/project

# Exclude specific directories
python scripts/detect_smells.py /path/to/project venv,tests,docs
```

**What it detects:**
- Long methods (>50 lines)
- Too many parameters (>5)
- Large classes (>15 methods)
- God classes (>20 methods)
- Magic numbers

#### Strategy 2: Manual Code Review

Read the code to identify design smells. See [smell-patterns.md](references/smell-patterns.md) for comprehensive catalog.

**Look for:**

**Code Quality Smells:**
- Duplicate code blocks
- Magic numbers (unexplained numeric literals)
- Hardcoded values (paths, URLs, config)
- Commented-out code
- Inconsistent naming

**Design Smells:**
- God classes (too many responsibilities)
- Feature envy (method uses more from another class)
- Inappropriate intimacy (classes too coupled)
- Data clumps (same parameters repeated)
- Primitive obsession (using primitives instead of objects)
- Long parameter lists (>5 parameters)

**Search patterns:**
```bash
# Find long files (potential large classes)
find . -name "*.py" -exec wc -l {} + | awk '$1 > 300'

# Find magic numbers (basic pattern)
grep -r "[^0-9]\d\{3,\}" --include="*.py" .

# Find hardcoded paths
grep -r '"/.*/"' --include="*.py" .

# Find commented code
grep -r "^[ ]*#.*def \|^[ ]*#.*class " --include="*.py" .
```

#### Strategy 3: Use External Tools

**radon** - Complexity metrics:
```bash
# Install
pip install radon

# Check cyclomatic complexity
radon cc /path/to/project -a

# Maintainability index
radon mi /path/to/project

# Show only complex functions
radon cc /path/to/project -nc
```

**pylint** - Code quality:
```bash
pip install pylint

# Check for code smells
pylint /path/to/project --disable=C0111  # Disable docstring warnings
```

### 3. Categorize Smells

Organize findings by severity and type.

See [smell-patterns.md](references/smell-patterns.md) for detailed patterns.

#### High Severity

**Immediate attention needed:**
- God classes (>20 methods, multiple responsibilities)
- Shotgun surgery (changes ripple across many files)
- Feature envy (method belongs in different class)
- Long parameter lists (>7 parameters)

#### Medium Severity

**Should refactor soon:**
- Large classes (>15 methods)
- Duplicate code
- Data clumps
- Primitive obsession
- Inappropriate intimacy

#### Low Severity

**Nice to improve:**
- Magic numbers
- Hardcoded values
- Inconsistent naming
- Lazy classes
- Commented-out code

### 4. Identify Refactorings

For each smell, determine appropriate refactoring.

See [refactoring-patterns.md](references/refactoring-patterns.md) for detailed examples.

**Common mappings:**

| Smell | Refactoring |
|-------|-------------|
| God class | Extract Class, Extract Service |
| Feature envy | Move Method |
| Duplicate code | Extract Method, Pull Up Method |
| Data clumps | Introduce Parameter Object |
| Magic numbers | Replace with Symbolic Constant |
| Long parameter list | Introduce Parameter Object |
| Primitive obsession | Replace Data Value with Object |
| Inappropriate intimacy | Move Method, Hide Delegate |
| Shotgun surgery | Move Method, Inline Class |
| Lazy class | Inline Class, Collapse Hierarchy |

### 5. Generate Report

Create a structured markdown report with specific refactoring recommendations.

## Code Smell Analysis Report

**Project:** [Project Name]
**Analyzed:** [Date]
**Scope:** [Directories analyzed]
**Excluded:** [Excluded directories]

---

## Summary

- **High severity smells:** X issues
- **Medium severity smells:** Y issues
- **Low severity smells:** Z issues

**Total:** N code smells detected

---

## 🔴 High Severity Smells

### Smell 1: God Class

**Location:** `src/services/user_manager.py:15`

**Class:** `UserManager`

**Description:** Class has 28 methods handling multiple unrelated responsibilities (user CRUD, authentication, email, logging, analytics).

**Impact:**
- Violates Single Responsibility Principle
- Hard to test and maintain
- Changes ripple across unrelated features

**Refactoring:** Extract Class

**Recommendation:**

Split into focused classes by responsibility:

```python
# Before: God class with 28 methods
class UserManager:
    def create_user(self, data): pass
    def update_user(self, user_id, data): pass
    def delete_user(self, user_id): pass
    def authenticate(self, username, password): pass
    def hash_password(self, password): pass
    def send_welcome_email(self, user): pass
    def send_password_reset(self, user): pass
    def log_activity(self, user, action): pass
    def get_statistics(self, user): pass
    # ... 19 more methods

# After: Split by responsibility
class UserRepository:
    """Handles user persistence."""
    def create(self, data): pass
    def update(self, user_id, data): pass
    def delete(self, user_id): pass
    def find_by_id(self, user_id): pass

class UserAuthService:
    """Handles authentication."""
    def authenticate(self, username, password): pass
    def hash_password(self, password): pass
    def validate_password_strength(self, password): pass

class UserNotificationService:
    """Handles user notifications."""
    def se
abstract-domain-explorerSkill

Applies abstract interpretation using different abstract domains (intervals, octagons, polyhedra, sign, congruence) to statically analyze program variables and infer invariants, value ranges, and relationships. Use when analyzing program properties, inferring loop invariants, detecting potential errors, or understanding variable relationships through static analysis.

abstract-invariant-generatorSkill

Uses abstract interpretation to automatically infer loop invariants, function preconditions, and postconditions for formal verification. Generates invariants that capture program behavior and support correctness proofs in Dafny, Isabelle, Coq, and other verification systems. Use when adding formal specifications to code, generating verification conditions, inferring contracts for functions, or discovering loop invariants for proofs.

abstract-state-analyzerSkill

Performs abstract interpretation over source code to infer possible program states, variable ranges, and data properties without executing the program. Reports potential runtime errors including out-of-bounds accesses, null dereferences, type inconsistencies, division by zero, and integer overflows. Use when analyzing code for potential runtime errors, performing static analysis, checking safety properties, or verifying program behavior without execution.

abstract-trace-summarizerSkill

Performs abstract interpretation to produce summarized execution traces and high-level program behavior representations. Highlights key control flow paths, variable relationships, loop invariants, function summaries, and potential runtime states using abstract domains (intervals, signs, nullness, etc.). Use when analyzing program behavior, understanding execution paths, computing loop invariants, tracking variable ranges, detecting potential runtime errors, or generating program summaries without concrete execution.

acsl-annotation-assistantSkill

Create ACSL (ANSI/ISO C Specification Language) formal annotations for C/C++ programs. Use this skill when working with formal verification, adding function contracts (requires/ensures), loop invariants, assertions, memory safety annotations, or any ACSL specifications. Supports Frama-C verification and generates comprehensive formal specifications for C/C++ code.

agent-browserSkill

CLI-based browser automation with persistent page state using ref-based element interaction. Use when users ask to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.

ambiguity-detectorSkill

Detects and analyzes ambiguous language in software requirements and user stories. Use when reviewing requirements documents, user stories, specifications, or any software requirement text to identify vague quantifiers, unclear scope, undefined terms, missing edge cases, subjective language, and incomplete specifications. Provides detailed analysis with clarifying questions and suggested improvements.

api-design-assistantSkill

Design and review APIs with suggestions for endpoints, parameters, return types, and best practices. Use when designing new APIs from requirements, reviewing existing API designs, generating API documentation, or getting implementation guidance. Supports REST APIs with focus on endpoint structure, request/response schemas, authentication, pagination, filtering, versioning, and OpenAPI specifications. Triggers when users ask to design, review, document, or improve APIs.