internal/skills/content/refactoring/SKILL.md
Technical debt remediation and code restructuring workflow. Use when improving code structure, reducing complexity, extracting abstractions, or paying down accumulated technical debt.
npx skillsauth add ar4mirez/samuel refactoringInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Structured approach to technical debt remediation. Improve code structure while maintaining behavior through incremental, safe changes.
| Trigger | Description | |---------|-------------| | Guardrail Violations | Functions >50 lines, files >300 lines | | Complexity Threshold | Cyclomatic complexity >10 | | Code Duplication | Same logic in 3+ places | | Quarterly Review | Regular technical debt assessment | | Pre-Feature | Before adding features to messy code | | Post-Incident | After bugs caused by confusing code |
Before starting:
Phase 1: Identify Candidates
↓
Phase 2: Impact Analysis
↓
Phase 3: Plan Refactoring
↓
Phase 4: Add Safety Net
↓
Phase 5: Execute Incrementally
↓
Phase 6: Validate & Document
Long Functions (>50 lines):
# Find functions over 50 lines (varies by language)
# Example: use linter rules or IDE features
Long Files (>300 lines):
# Find files over 300 lines
find src -name "*.ts" -exec wc -l {} \; | awk '$1 > 300'
find src -name "*.py" -exec wc -l {} \; | awk '$1 > 300'
High Complexity:
# Use complexity analyzers
npx escomplex src/**/*.ts
python -m mccabe src/**/*.py
| Smell | Signs | Priority | |-------|-------|----------| | Long Method | >50 lines, multiple responsibilities | High | | Large Class | >300 lines, low cohesion | High | | Feature Envy | Method uses other class more than own | Medium | | Data Clumps | Same group of variables together | Medium | | Primitive Obsession | Overuse of primitives vs objects | Medium | | Switch Statements | Large switch blocks | Low | | Speculative Generality | Unused abstractions | Low |
Document identified candidates:
## Refactoring Candidates
### High Priority
| File | Issue | Lines | Impact |
|------|-------|-------|--------|
| src/services/order.ts | Long method: processOrder | 120 → 50 | High |
| src/api/users.ts | Large file | 450 → 200 | High |
| src/utils/validation.ts | Duplication | N/A | Medium |
### Medium Priority
| File | Issue | Lines | Impact |
|------|-------|-------|--------|
| src/models/product.ts | Feature envy | N/A | Medium |
| src/services/email.ts | Complex conditionals | N/A | Medium |
For each candidate, identify:
Target: src/services/order.ts
Dependencies (imports from):
- src/models/order.ts
- src/services/inventory.ts
- src/services/payment.ts
Dependents (imported by):
- src/api/orders.ts
- src/workers/orderProcessor.ts
- tests/services/order.test.ts
Impact radius: 5 files
Risk level: Medium
| Factor | Low | Medium | High | |--------|-----|--------|------| | Test coverage | >80% | 60-80% | <60% | | Dependents | <3 | 3-10 | >10 | | Business criticality | Non-critical | Important | Critical path | | Complexity | Simple rename | Extract method | Architecture change |
Low Effort High Effort
┌────────────┬────────────┐
High Value │ DO FIRST │ PLAN │
│ │ CAREFULLY │
├────────────┼────────────┤
Low Value │ QUICK WIN │ AVOID │
│ │ │
└────────────┴────────────┘
| Smell | Technique | Description | |-------|-----------|-------------| | Long method | Extract Method | Pull out logical chunks | | Large class | Extract Class | Split by responsibility | | Feature envy | Move Method | Move to appropriate class | | Data clumps | Extract Parameter Object | Group related params | | Duplicated code | Extract to shared function | DRY principle | | Complex conditional | Replace with polymorphism | Strategy pattern | | Long parameter list | Introduce Parameter Object | Create wrapper class |
Example: Extract Method from Long Function
## Refactoring Plan: processOrder()
### Goal
Reduce processOrder() from 120 lines to <50 lines
### Steps
1. [ ] Add characterization tests for current behavior
2. [ ] Extract validateOrder() (lines 15-35)
3. [ ] Verify tests pass
4. [ ] Commit: "refactor: extract validateOrder"
5. [ ] Extract calculateTotals() (lines 40-65)
6. [ ] Verify tests pass
7. [ ] Commit: "refactor: extract calculateTotals"
8. [ ] Extract processPayment() (lines 70-95)
9. [ ] Verify tests pass
10. [ ] Commit: "refactor: extract processPayment"
11. [ ] Extract sendConfirmation() (lines 100-115)
12. [ ] Verify tests pass
13. [ ] Commit: "refactor: extract sendConfirmation"
14. [ ] Final cleanup and documentation
15. [ ] Commit: "refactor: cleanup processOrder"
### Expected Result
- processOrder(): 120 → 25 lines
- New methods: 4
- Total lines: +10 (net increase for clarity)
Before refactoring, add tests that capture current behavior:
describe('processOrder - characterization tests', () => {
it('should match current behavior for valid order', () => {
const order = createValidOrder();
const result = processOrder(order);
// Capture current output exactly
expect(result).toMatchSnapshot();
});
it('should match current behavior for edge cases', () => {
const edgeCases = [
createEmptyOrder(),
createMaxItemOrder(),
createDiscountedOrder(),
];
edgeCases.forEach(order => {
expect(processOrder(order)).toMatchSnapshot();
});
});
});
Ensure adequate coverage before proceeding:
# Check coverage for target file
npm test -- --coverage --collectCoverageFrom="src/services/order.ts"
Minimum Coverage: 60% before refactoring (prefer >80%)
Create a checkpoint before starting:
git add .
git commit -m "chore: checkpoint before refactoring processOrder"
Bad: Multiple changes in one commit
# Too much at once - hard to debug if tests fail
git commit -m "refactor: refactor entire order module"
Good: Atomic changes
git commit -m "refactor(order): extract validateOrder method"
git commit -m "refactor(order): extract calculateTotals method"
git commit -m "refactor(order): extract processPayment method"
For each change:
1. Run tests → PASS (green)
2. Make one refactoring change
3. Run tests → Should still PASS (green)
4. If FAIL (red) → Revert and try smaller change
5. If PASS → Commit
6. Repeat
See references/process.md for detailed code examples including:
Update patterns.md (if new pattern emerged):
## Order Processing Pattern
Orders are processed through composable steps:
1. validateOrder() - Input validation
2. calculateTotals() - Price calculations
3. processPayment() - Payment handling
4. sendConfirmation() - Notifications
Create memory entry (if significant):
# Refactoring: Order Processing
**Date**: 2025-01-15
**Files**: src/services/order.ts
## Before
- Single 120-line function
- Difficult to test
- Hard to modify
## After
- 5 focused functions (<30 lines each)
- Easier to test
- Clear responsibilities
## Lessons
- Extract Method is low-risk, high-reward
- Characterization tests prevented regressions
git add .
git commit -m "refactor(order): complete processOrder decomposition
- Extract validateOrder (20 lines)
- Extract calculateTotals (25 lines)
- Extract processPayment (30 lines)
- Extract sendConfirmation (20 lines)
- Main function now 25 lines (was 120)
No behavior changes. All tests passing."
| Refactoring | When | Effort | Risk | |-------------|------|--------|------| | Rename | Unclear naming | Low | Low | | Extract Method | Long function | Low | Low | | Extract Variable | Complex expression | Low | Low | | Inline | Over-abstraction | Low | Low | | Extract Class | Large class | Medium | Medium | | Move Method | Feature envy | Medium | Medium | | Extract Parameter Object | Long param list | Medium | Low | | Replace Conditional with Polymorphism | Complex switch | High | Medium | | Replace Inheritance with Composition | Rigid hierarchy | High | High |
Most refactorings have IDE shortcuts:
| Action | VS Code | JetBrains | |--------|---------|-----------| | Rename | F2 | Shift+F6 | | Extract Method | Ctrl+Shift+R | Ctrl+Alt+M | | Extract Variable | Ctrl+Shift+R | Ctrl+Alt+V | | Move | Drag or F2 | F6 | | Inline | N/A | Ctrl+Alt+N |
references/process.md for code patternsdevelopment
Zig language guardrails, patterns, and best practices for AI-assisted development. Use when working with Zig files (.zig), build.zig, or when the user mentions Zig. Provides comptime patterns, allocator conventions, C interop guidelines, and testing standards specific to this project's coding standards.
tools
WordPress framework guardrails, patterns, and best practices for AI-assisted development. Use when working with WordPress projects, or when the user mentions WordPress. Provides theme development, plugin architecture, REST API, blocks, and security guidelines.
tools
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs. Use when testing web apps, automating browser interactions, or debugging frontend issues.
tools
Suite of tools for creating elaborate, multi-component web applications using modern frontend technologies (React, Tailwind CSS, shadcn/ui). Use for complex projects requiring state management, routing, or shadcn/ui components - not for simple single-file HTML/JSX pages.