Refactor Skill
Collaborating skills
- TDD: skill:
tddfor guiding through Red-Green-Refactor cycles and ensuring tests are in place before refactoring - Design Patterns: skill:
design-pattern-adopterfor guidance on applying design patterns effectively
Quick Reference
Code Smells Reference
| Smell | Detection | Refactoring |
|---|---|---|
| Long function | >20 lines | Extract Method |
| Duplicated code | Similar logic | Extract Method, Pull Up |
| Long parameter list | >3 params | Introduce Parameter Object |
| Large class | >10 methods | Extract Class |
| Feature envy | Method uses other class | Move Method |
| Switch statements | Type checking | Replace with Polymorphism |
| Speculative generality | Unused abstractions | Inline, Collapse Hierarchy |
| Message chains | a.b.c.d | Hide Delegate |
| Middle man | Excessive delegation | Remove Middle Man |
| Incomplete library class | Missing methods | Introduce Foreign Method |
Process
1. VERIFY - Tests exist and pass
2. ANALYZE - Identify code smells (see references/code-smells.md)
3. SELECT - Choose appropriate pattern (see references/catalog.md)
4. APPLY - One small step at a time
5. VERIFY - Run tests after each change
6. REPEAT - Until clean
TDD Cycle
For each discrete refactoring:
🔴 RED - If adding behavior, write failing test first
🟢 GREEN - Make minimal changes to pass tests
🔵 REFACTOR - Apply pattern while keeping tests green
✅ VERIFY - Run tests, lint, type check
Prerequisites
- Tests must exist - If no tests, write them first
- Tests must pass - Run tests before starting
- Understand the code - Read and comprehend behavior
Verification Commands
Python:
pytest # Run tests
ruff check src/ # Lint
mypy src/ # Type check
Ruby:
rspec # Run tests
rubocop # Lint
steep check # Type check (if using Steep)
Refactoring Checklist
- [ ] Function does one thing only (SRP)
- [ ] Function name clearly describes intent
- [ ] Function is 20 lines or fewer
- [ ] 3 or fewer parameters
- [ ] No duplicate code (DRY)
- [ ] If nesting is 2 levels or fewer
- [ ] No magic numbers
- [ ] Self-documenting code
- [ ] Tests pass
- [ ] Lint passes
- [ ] Type check passes
Constraints
MUST:
- Write/run tests before refactoring
- Change one thing at a time
- Preserve behavior exactly
MUST NOT:
- Refactor + add features simultaneously
- Refactor without tests
- Batch multiple refactorings
References
- Code Smells Guide - Detection patterns and fixes for all code smells
- Refactoring Catalog - Complete catalog with Ruby/Python examples
- Advanced Patterns - SOLID refactorings, prompt patterns, functional patterns