refactor
Code Refactoring Skill
A systematic approach to refactoring code based on Martin Fowler's *Refactoring: Improving the Design of Existing Code* (2nd Edition). This skill emphasizes safe, incremental changes backed by tests.
"Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure." — Martin Fowler
Core Principles
- Behavior Preservation: External behavior must remain unchanged
- Small Steps: Make tiny, testable changes
- Test-Driven: Tests are the safety net
- Continuous: Refactoring is ongoing, not a one-time event
- Collaborative: User approval required at each phase
Workflow Overview
Phase 1: Research & Analysis
↓
Phase 2: Test Coverage Assessment
↓
Phase 3: Code Smell Identification
↓
Phase 4: Refactoring Plan Creation
↓
Phase 5: Incremental Implementation
↓
Phase 6: Review & IterationPhase 1: Research & Analysis
Objectives
- Understand the codebase structure and purpose
- Identify the scope of refactoring
- Gather context about business requirements
Questions to Ask User
Before starting, clarify:
- Scope: Which files/modules/functions need refactoring?
- Goals: What problems are you trying to solve? (readability, performance, maintainability)
- Constraints: Are there any areas that should NOT be changed?
- Timeline pressure: Is this blocking other work?
- Test status: Do tests exist? Are they passing?
Actions
- [ ] Read and understand the target code
- [ ] Identify dependencies and integrations
- [ ] Document current architecture
- [ ] Note any existing technical debt markers (TODOs, FIXMEs)
Output
Present findings to user:
- Code structure summary
- Identified problem areas
- Initial recommendations
- Request approval to proceed
Phase 2: Test Coverage Assessment
Why Tests Matter
"Refactoring without tests is like driving without a seatbelt." — Martin Fowler
Tests are the key enabler of safe refactoring. Without them, you risk introducing bugs.
Assessment Steps
- Check for existing tests
```bash
# Look for test files
find . -name "*test*" -o -name "*spec*" | head -20
```
- Run existing tests
```bash
# JavaScript/TypeScript
npm test
# Python
pytest -v
# Java
mvn test
```
- Check coverage (if available)
```bash
# JavaScript
npm run test:coverage
# Python
pytest --cov=.
```
Decision Point: Ask User
If tests exist and pass:
- Proceed to Phase 3
If tests are missing or incomplete:
Present options:
- Write tests first (recommended)
- Add tests incrementally during refactoring
- Proceed without tests (risky - requires user acknowledgment)
If tests are failing:
- STOP. Fix failing tests before refactoring
- Ask user: Should we fix tests first?
Test Writing Guidelines (if needed)
For each function being refactored, ensure tests cover:
- Happy path (normal operation)
- Edge cases (empty inputs, null, boundaries)
- Error scenarios (invalid inputs, exceptions)
Use the "red-green-refactor" cycle:
- Write failing test (red)
- Make it pass (green)
- Refactor
Phase 3: Code Smell Identification
What Are Code Smells?
Symptoms of deeper problems in code. They're not bugs, but indicators that the code could be improved.
Common Code Smells to Check
See references/code-smells.md for the complete catalog.
#### Quick Reference
| Smell | Signs | Impact |
|-------|-------|--------|
| Long Method | Methods > 30-50 lines | Hard to understand, test, maintain |
| Duplicated Code | Same logic in multiple places | Bug fixes needed in multiple places |
| Large Class | Class with too many responsibilities | Violates Single Responsibility |
| Feature Envy | Method uses another class's data more | Poor encapsulation |
| Primitive Obsession | Overuse of primitives instead of objects | Missing domain concepts |
| Long Parameter List | Methods with 4+ parameters | Hard to call correctly |
| Data Clumps | Same data items appearing together | Missing abstraction |
| Switch Statements | Complex switch/if-else chains | Hard to extend |
| Speculative Generality | Code "just in case" | Unnecessary complexity |
| Dead Code | Unused code | Confusion, maintenance burden |
Analysis Steps
- Automated Analysis (if scripts available)
```bash
python scripts/detect-smells.py <file>
```
- Manual Review
- Walk through code systematically
- Note each smell with location and severity
- Categorize by impact (Critical/High/Medium/Low)
- Prioritization
Focus on smells that:
- Block current development
- Cause bugs or confusion
- Affect most-changed code paths
Output: Smell Report
Present to user:
- List of identified smells with locations
- Severity assessment for each
- Recommended priority order
- Request approval on priorities
Phase 4: Refactoring Plan Creation
Selecting Refactorings
For each smell, select an appropriate refactoring from the catalog.
See references/refactoring-catalog.md for the complete list.
#### Smell-to-Refactoring Mapping
| Code Smell | Recommended Refactoring(s) |
|------------|---------------------------|
| Long Method | Extract Method, Replace Temp with Query |
| Duplicated Code | Extract Method, Pull Up Method, Form Template Method |
| Large Class | Extract Class, Extract Subclass |
