with one click
refactoring-patterns
Apply safe refactoring patterns to improve code structure without changing behavior. Use when cleaning up code, reducing technical debt, or improving maintainability.
Menu
Apply safe refactoring patterns to improve code structure without changing behavior. Use when cleaning up code, reducing technical debt, or improving maintainability.
| name | refactoring-patterns |
| description | Apply safe refactoring patterns to improve code structure without changing behavior. Use when cleaning up code, reducing technical debt, or improving maintainability. |
| category | development-practices |
| priority | medium |
| tokenEstimate | 1000 |
| agents | ["qe-code-reviewer","qe-quality-analyzer","qe-test-refactorer"] |
| implementation_status | optimized |
| optimization_version | 1 |
| last_optimized | "2025-12-03T00:00:00.000Z" |
| dependencies | [] |
| quick_reference_card | true |
| tags | ["refactoring","code-quality","technical-debt","maintainability","clean-code"] |
| trust_tier | 2 |
| validation | {"schema_path":"schemas/output.json","validator_path":"scripts/validate-config.json"} |
<default_to_action> When refactoring:
Safe Refactoring Cycle:
npm test # Green ✅
# Make ONE small change
npm test # Still green ✅
git commit -m "refactor: extract calculateTotal"
# Repeat
Code Smells → Refactoring:
| Smell | Refactoring |
|---|---|
| Long method (>20 lines) | Extract Method |
| Large class | Extract Class |
| Long parameter list (>3) | Introduce Parameter Object |
| Duplicated code | Extract Method/Class |
| Complex conditional | Decompose Conditional |
| Magic numbers | Named Constants |
| Nested loops | Replace Loop with Pipeline |
NEVER REFACTOR:
| Pattern | Before | After |
|---|---|---|
| Extract Method | 50-line function | 5 small functions |
| Extract Class | Class doing 5 things | 5 single-purpose classes |
| Parameter Object | fn(a,b,c,d,e,f) | fn(options) |
| Replace Conditional | if (type === 'a') {...} | Polymorphism |
| Pipeline | Nested loops | .filter().map().reduce() |
// Before: Long method
function processOrder(order) {
// 50 lines of validation, calculation, saving, emailing...
}
// After: Clear responsibilities
function processOrder(order) {
validateOrder(order);
const pricing = calculatePricing(order);
const saved = saveOrder(order, pricing);
sendConfirmationEmail(saved);
return saved;
}
// Before
let results = [];
for (let item of items) {
if (item.inStock) {
results.push(item.name.toUpperCase());
}
}
// After
const results = items
.filter(item => item.inStock)
.map(item => item.name.toUpperCase());
// Before
if (order.total > 1000 && customer.isPremium && allInStock(order)) {
return 'FREE_SHIPPING';
}
// After
function isEligibleForFreeShipping(order, customer) {
return isLargeOrder(order) &&
isPremiumCustomer(customer) &&
allInStock(order);
}
| ❌ Anti-Pattern | Problem | ✅ Better |
|---|---|---|
| Without tests | No safety net | Write tests first |
| Big bang | Rewrite everything | Small incremental steps |
| For perfection | Endless tweaking | Good enough, move on |
| Premature abstraction | Pattern not clear yet | Wait for Rule of Three |
| During feature work | Mixed changes | Separate commits |
// Detect code smells
const smells = await Task("Detect Code Smells", {
source: 'src/services/',
patterns: ['long-method', 'large-class', 'duplicate-code']
}, "qe-quality-analyzer");
// Safe refactoring with test verification
await Task("Verify Refactoring", {
beforeCommit: 'abc123',
afterCommit: 'def456',
expectSameBehavior: true
}, "qe-test-executor");
aqe/refactoring/
├── smells/* - Detected code smells
├── suggestions/* - Refactoring recommendations
├── verifications/* - Behavior preservation checks
└── history/* - Refactoring log
const refactoringFleet = await FleetManager.coordinate({
strategy: 'refactoring',
agents: [
'qe-quality-analyzer', // Identify targets
'qe-test-generator', // Add safety tests
'qe-test-executor', // Verify behavior
'qe-test-refactorer' // TDD refactor phase
],
topology: 'sequential'
});
Refactoring is NOT:
Refactoring IS:
Always have tests. Always take small steps. Always keep tests green.
End-to-end npm release workflow with verification gates and hardcoded-version protection
Chaos engineering principles, controlled failure injection, resilience testing, and system recovery validation. Use when testing distributed systems, building confidence in fault tolerance, or validating disaster recovery.
Test quality validation through mutation testing, assessing test suite effectiveness by introducing code mutations and measuring kill rate. Use when evaluating test quality, identifying weak tests, or proving tests actually catch bugs.
Injects controlled faults (network partition, latency, process kill, disk pressure) into distributed systems and validates recovery behavior. Use when testing circuit breakers, failover paths, retry logic, or building confidence in system resilience through chaos engineering.
Analyzes test coverage data (Istanbul, c8, lcov) to identify uncovered lines, branches, and functions with risk-weighted gap detection. Use when analyzing coverage reports, identifying coverage gaps, comparing coverage between branches, or prioritizing which untested code to cover first.
Evaluates code quality through complexity analysis, lint results, code smell detection, and test health metrics. Use when assessing deployment readiness, configuring quality gates, scoring a codebase for release, or generating quality reports with pass/fail verdicts.