refactoring-patterns
Apply safe refactoring patterns to improve code structure without changing behavior. Use when cleaning up code, reducing technical debt, or improving maintainability.
Best use case
refactoring-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Apply safe refactoring patterns to improve code structure without changing behavior. Use when cleaning up code, reducing technical debt, or improving maintainability.
Teams using refactoring-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/refactoring-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How refactoring-patterns Compares
| Feature / Agent | refactoring-patterns | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Apply safe refactoring patterns to improve code structure without changing behavior. Use when cleaning up code, reducing technical debt, or improving maintainability.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
Cursor vs Codex for AI Workflows
Compare Cursor and Codex for AI coding workflows, repository assistance, debugging, refactoring, and reusable developer skills.
SKILL.md Source
# Refactoring Patterns
<default_to_action>
When refactoring:
1. ENSURE tests pass (never refactor without tests)
2. MAKE small change (one refactoring at a time)
3. RUN tests (must stay green)
4. COMMIT (save progress)
5. REPEAT
**Safe Refactoring Cycle:**
```bash
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:**
- Without tests (write tests first)
- When deadline is tomorrow
- Code you don't understand
- Code that works and won't be touched
</default_to_action>
## Quick Reference Card
### Common Refactorings
| 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()` |
### The Rule of Three
1. First time → Just do it
2. Second time → Wince and duplicate
3. Third time → **Refactor**
---
## Key Patterns
### Extract Method
```javascript
// 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;
}
```
### Replace Loop with Pipeline
```javascript
// 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());
```
### Decompose Conditional
```javascript
// Before
if (order.total > 1000 && customer.isPremium && allInStock(order)) {
return 'FREE_SHIPPING';
}
// After
function isEligibleForFreeShipping(order, customer) {
return isLargeOrder(order) &&
isPremiumCustomer(customer) &&
allInStock(order);
}
```
---
## Refactoring Anti-Patterns
| ❌ 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 |
---
## Agent Integration
```typescript
// 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");
```
---
## Agent Coordination Hints
### Memory Namespace
```
aqe/refactoring/
├── smells/* - Detected code smells
├── suggestions/* - Refactoring recommendations
├── verifications/* - Behavior preservation checks
└── history/* - Refactoring log
```
### Fleet Coordination
```typescript
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'
});
```
---
## Related Skills
- [tdd-london-chicago](../tdd-london-chicago/) - TDD refactor phase
- [code-review-quality](../code-review-quality/) - Review refactored code
- [xp-practices](../xp-practices/) - Collective ownership
---
## Remember
**Refactoring is NOT:**
- Adding features
- Fixing bugs
- Performance optimization
- Rewriting from scratch
**Refactoring IS:**
- Improving structure
- Making code clearer
- Reducing complexity
- Removing duplication
- **Without changing behavior**
**Always have tests. Always take small steps. Always keep tests green.**Related Skills
qe-refactoring-patterns
Apply safe refactoring patterns to improve code structure without changing behavior. Use when cleaning up code, reducing technical debt, or improving maintainability.
qe-observability-testing-patterns
Observability and monitoring validation patterns for dashboards, alerting, log aggregation, APM traces, and SLA/SLO verification. Use when testing monitoring infrastructure, dashboard accuracy, alert rules, or metric pipelines.
qe-n8n-integration-testing-patterns
API contract testing, authentication flows, rate limit handling, and error scenario coverage for n8n integrations with external services. Use when testing n8n node integrations.
qe-middleware-testing-patterns
Enterprise middleware testing patterns for message routing, transformation, DLQ, protocol mediation, ESB error handling, and EIP patterns. Use when testing middleware layers, message brokers, ESBs, or integration buses.
qe-api-testing-patterns
Comprehensive API testing patterns including contract testing, REST/GraphQL testing, and integration testing. Use when testing APIs or designing API test strategies.
wms-testing-patterns
Warehouse Management System testing patterns for inventory operations, pick/pack/ship workflows, wave management, EDI X12/EDIFACT compliance, RF/barcode scanning, and WMS-ERP integration. Use when testing WMS platforms (Blue Yonder, Manhattan, SAP EWM).
observability-testing-patterns
Observability and monitoring validation patterns for dashboards, alerting, log aggregation, APM traces, and SLA/SLO verification. Use when testing monitoring infrastructure, dashboard accuracy, alert rules, or metric pipelines.
n8n-integration-testing-patterns
API contract testing, authentication flows, rate limit handling, and error scenario coverage for n8n integrations with external services. Use when testing n8n node integrations.
middleware-testing-patterns
Enterprise middleware testing patterns for message routing, transformation, DLQ, protocol mediation, ESB error handling, and EIP patterns. Use when testing middleware layers, message brokers, ESBs, or integration buses.
api-testing-patterns
Comprehensive API testing patterns including contract testing, REST/GraphQL testing, and integration testing. Use when testing APIs or designing API test strategies.
qe-wms-testing-patterns
Warehouse Management System testing patterns for inventory operations, pick/pack/ship workflows, wave management, EDI X12/EDIFACT compliance, RF/barcode scanning, and WMS-ERP integration. Use when testing WMS platforms (Blue Yonder, Manhattan, SAP EWM).
AgentDB Memory Patterns
Implement persistent memory patterns for AI agents using AgentDB. Includes session memory, long-term storage, pattern learning, and context management. Use when building stateful agents, chat systems, or intelligent assistants.