design-smell-detector
Identify design quality issues in code including high coupling, low cohesion, God classes, long methods, and other code smells. Use when: (1) Reviewing code architecture and design quality, (2) Identifying refactoring opportunities, (3) Detecting God classes or classes with too many responsibilities, (4) Finding high coupling or low cohesion issues, (5) Analyzing code maintainability and technical debt. Detects coupling smells, cohesion problems, complexity issues, size violations, and encapsulation problems with actionable refactoring suggestions.
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/design-smell-detector && cp -r /tmp/design-smell-detector/skills/design-smell-detector ~/.claude/skills/design-smell-detectorSKILL.md
# Design Smell Detector
Identify and address design quality issues in code through automated smell detection and refactoring guidance.
## Quick Start
### Detect Design Smells
```bash
# Analyze a single file
python scripts/detect_smells.py src/app.py
# Analyze entire directory
python scripts/detect_smells.py src/
# Output as JSON
python scripts/detect_smells.py src/ --format json
```
### Example Output
```
Found 5 design smell(s): 1 critical, 3 major, 1 minor
CRITICAL ISSUES:
🔴 src/services.py:45 - God Class
Class 'UserManager' has 25 methods (threshold: 20)
💡 Split into multiple smaller, focused classes
MAJOR ISSUES:
🟠 src/models.py:120 - Low Cohesion
Class 'Order' has low cohesion (score: 0.25)
💡 Group related methods/attributes or split class
🟠 src/utils.py:89 - Long Method
Method 'process_order' has 67 lines (threshold: 50)
💡 Extract smaller methods or refactor
```
## Design Smells Detected
### Coupling Smells
**High Coupling**: Too many dependencies
- Module imports > 20
- Constructor dependencies > 10
- Changes cascade across classes
**Feature Envy**: Method uses other class more than own
- External access > internal access
- Method should move to envied class
**Inappropriate Intimacy**: Classes too tightly coupled
- Accessing private fields of other classes
- Excessive use of getters/setters
### Cohesion Smells
**Low Cohesion**: Class members unrelated
- LCOM (Lack of Cohesion) > 0.7
- Methods don't share instance variables
- Class has multiple responsibilities
**God Class**: Class knows/does too much
- Methods > 20
- Attributes > 15
- Lines of code > 500
### Complexity Smells
**High Cyclomatic Complexity**: Too many decision points
- Complexity > 10
- Deeply nested conditionals
- Many if/else, loops
**Long Method**: Method too long
- Lines of code > 50
- Multiple responsibilities
- Hard to understand
### Size Smells
**Long Parameter List**: Too many parameters
- Parameters > 5
- Related parameters not grouped
- Method signature hard to understand
**Large Module**: Module too large
- Classes > 20
- Lines of code > 1000
- Multiple responsibilities
### Encapsulation Smells
**Data Class**: Only data, no behavior
- Only getters/setters
- No business logic
- Missing encapsulation
**Exposed Internal State**: Implementation details exposed
- Public mutable fields
- Returns references to internal collections
- Breaks encapsulation
## Detection Workflow
### 1. Run Detection
Analyze codebase for design smells:
```bash
python scripts/detect_smells.py src/
```
### 2. Review Results
Examine detected smells by severity:
- **Critical**: God classes, severe coupling issues
- **Major**: Low cohesion, long methods, high complexity
- **Minor**: Long parameter lists, feature envy
### 3. Prioritize Refactoring
Focus on:
- Critical issues first
- Frequently changed code
- High-impact, low-effort improvements
### 4. Apply Refactoring
Use refactoring strategies based on smell type.
See **[refactoring_strategies.md](references/refactoring_strategies.md)** for detailed solutions.
### 5. Verify Improvements
Re-run detection to measure progress:
```bash
python scripts/detect_smells.py src/
```
Compare metrics before/after.
## Common Design Smells
### God Class
**Symptoms**:
- Too many methods (>20)
- Too many attributes (>15)
- Low cohesion
- Multiple responsibilities
**Example**:
```python
# ❌ God Class
class Application:
# 30+ methods handling:
# - User management
# - Order processing
# - Payment handling
# - Reporting
# - Email notifications
# - File operations
pass
```
**Refactoring**:
```python
# ✅ Split by responsibility
class UserManager:
pass
class OrderProcessor:
pass
class PaymentHandler:
pass
class ReportGenerator:
pass
```
### High Coupling
**Symptoms**:
- Too many imports (>20)
- Too many constructor dependencies
- Changes cascade across classes
**Example**:
```python
# ❌ High coupling
class UserService:
def __init__(self):
self.db = Database()
self.cache = Cache()
self.logger = Logger()
self.validator = Validator()
self.email = EmailService()
self.sms = SMSService()
# ... many more
```
**Refactoring**:
```python
# ✅ Dependency injection
class UserService:
def __init__(self, db, logger, notifier):
self.db = db
self.logger = logger
self.notifier = notifier # Abstraction
```
### Low Cohesion
**Symptoms**:
- Methods don't share attributes
- Class does unrelated things
- LCOM score > 0.7
**Example**:
```python
# ❌ Low cohesion
class UserManager:
def create_user(self):
pass
def send_email(self):
pass
def log_activity(self):
pass
def calculate_discount(self):
pass
```
**Refactoring**:
```python
# ✅ High cohesion - focused classes
class UserRepository:
def create_user(self):
pass
class EmailService:
def send_email(self):
pass
class ActivityLogger:
def log_activity(self):
pass
```
### Long Method
**Symptoms**:
- Method > 50 lines
- Multiple responsibilities
- Hard to understand
**Example**:
```python
# ❌ Long method (100+ lines)
def process_order(order):
# Validate (20 lines)
# Calculate price (15 lines)
# Save to DB (10 lines)
# Send email (20 lines)
# Update stats (10 lines)
# Log activity (15 lines)
pass
```
**Refactoring**:
```python
# ✅ Extract methods
def process_order(order):
validate_order(order)
total = calculate_total(order)
save_order(order, total)
send_confirmation(order)
update_statistics()
log_activity(order)
```
## Refactoring Strategies
### Reduce Coupling
**Dependency Injection**:
```python
# Inject dependencies instead of creating them
class OrderService:
def __init__(self, db, logger):
self.db = db
self.logger = logger
```
**Interface Abstraction**:
```python
# Depend on abstractions,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.
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.
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.
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.
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.
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.
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.
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.