refactor
Analyze code for SOLID violations and suggest targeted improvements
What this skill does
# SOLID Refactoring Assistant
Analyze code for SOLID violations and suggest targeted improvements.
## Purpose
Identify refactoring opportunities based on:
- SOLID principle violations
- Code smells and anti-patterns
- Complexity metrics
- Duplication detection
## Instructions
### Step 1: Scope Analysis
Determine the refactoring scope from user input:
- Single file: Deep analysis
- Directory: Pattern detection across files
- Function/class: Focused extraction suggestions
```bash
# Get file/directory stats
if [ -f "$TARGET" ]; then
wc -l "$TARGET"
echo "Single file analysis"
elif [ -d "$TARGET" ]; then
find "$TARGET" -type f \( -name "*.ts" -o -name "*.js" -o -name "*.py" \) | wc -l
echo "Directory analysis"
fi
```
### Step 2: SOLID Violations Detection
#### S - Single Responsibility
Look for:
- Files > 300 lines
- Functions > 50 lines
- Classes with > 10 methods
- Mixed concerns (data + UI + business logic)
```bash
# Find large files
find . -name "*.{ts,js,py}" -exec wc -l {} + 2>/dev/null | sort -rn | head -10
# Functions with high line count (approximate)
grep -rn "function\|def \|fn " --include="*.{ts,js,py,rs}" . | head -20
```
#### O - Open/Closed Principle
Look for:
- Switch/case statements on types
- Repeated if/else type checking
- Direct modifications vs extensions
#### L - Liskov Substitution
Look for:
- Overridden methods that throw "not implemented"
- Type checks before method calls
- Empty method overrides
#### I - Interface Segregation
Look for:
- Large interfaces (> 10 methods)
- Classes implementing unused interface methods
- Fat service classes
#### D - Dependency Inversion
Look for:
- Direct instantiation of dependencies (`new Service()`)
- Hardcoded class references
- Missing dependency injection
### Step 3: Code Smells
```bash
# Duplication patterns
grep -rn --include="*.{ts,js,py}" . 2>/dev/null | \
awk -F: '{print $3}' | sort | uniq -c | sort -rn | head -10
# Long parameter lists (> 4 params)
grep -rn "function.*,.*,.*,.*," --include="*.{ts,js}" . 2>/dev/null | head -10
# Deep nesting (4+ levels)
grep -rn "^\s\{16,\}" --include="*.{ts,js,py}" . 2>/dev/null | head -10
```
### Step 4: Complexity Assessment
For each issue found, assess:
- **Impact**: How much code is affected?
- **Risk**: What could break?
- **Effort**: Lines to change, tests needed?
## Output Format
---
### ๐ง Refactoring Analysis
**Target**: [file/directory]
**Lines Analyzed**: [count]
### ๐ SOLID Scorecard
| Principle | Status | Issues Found |
|-----------|--------|--------------|
| Single Responsibility | ๐ก | 3 large classes |
| Open/Closed | ๐ข | OK |
| Liskov Substitution | ๐ข | OK |
| Interface Segregation | ๐ด | 2 fat interfaces |
| Dependency Inversion | ๐ก | 5 direct instantiations |
### ๐ฏ Priority Refactorings
#### 1. [Highest Impact] - Extract class from `UserService`
**Violation**: Single Responsibility
**Current**: 450 lines handling auth + profile + notifications
**Suggested**:
```
UserService.ts (450 lines)
โ Extract
AuthService.ts (~150 lines)
ProfileService.ts (~150 lines)
NotificationService.ts (~100 lines)
```
**Risk**: Medium (update imports)
**Tests Needed**: Update dependency injection in tests
#### 2. [Second Priority] - Replace switch with polymorphism
**Location**: `src/handlers/payment.ts:45`
**Current**:
```typescript
switch (paymentType) {
case 'card': // 50 lines
case 'bank': // 50 lines
case 'crypto': // 50 lines
}
```
**Suggested**: Strategy pattern with `PaymentProcessor` interface
**Risk**: Low (isolated change)
### ๐ Code Smells
| Smell | Location | Severity |
|-------|----------|----------|
| Long Method | `api.ts:calculateTotal` (120 lines) | ๐ High |
| Duplicate Code | `utils/*.ts` (3 similar blocks) | ๐ก Medium |
| Deep Nesting | `parser.ts:parse` (6 levels) | ๐ก Medium |
### ๐ Quick Wins (Low Risk, High Value)
1. Extract `validateEmail()` to shared utils (used in 4 places)
2. Replace magic numbers with named constants
3. Add early returns to reduce nesting in `processOrder()`
### โ ๏ธ Technical Debt Notes
- [Item to track for future sprints]
---
## Refactoring Safety Checklist
Before applying suggestions:
- [ ] Tests exist for affected code
- [ ] Create feature branch
- [ ] Commit current state
- [ ] Apply one refactoring at a time
- [ ] Run tests after each change
- [ ] Review diff before committing
## Usage
**Analyze specific file:**
```
/refactor src/services/user.ts
```
**Analyze directory:**
```
/refactor src/api/
```
**Focus on specific principle:**
```
/refactor --focus=srp src/services/
```
**With complexity threshold:**
```
/refactor --threshold=high
```
## References
- Martin Fowler's Refactoring Catalog
- Clean Code by Robert C. Martin
- SOLID principles by Robert C. Martin
$ARGUMENTS
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.