Agent Skills
› cosmicstack-labs/mercury-agent-skills
› refactoring-patterns
refactoring-patterns
GitHub提供系统化重构技术,涵盖代码异味消除、模式提取及遗留系统现代化。包含标准工作流、具体重构手法(如提取方法、多态替换条件)及遗留代码策略,旨在安全提升代码质量。
Trigger Scenarios
需要重构长函数或复杂逻辑
处理遗留代码现代化
消除代码异味
优化条件判断结构
Install
npx skills add cosmicstack-labs/mercury-agent-skills --skill refactoring-patterns -g -y
SKILL.md
Frontmatter
{
"name": "refactoring-patterns",
"metadata": {
"tags": [
"refactoring",
"code-quality",
"patterns",
"legacy",
"modernization"
],
"author": "cosmicstack-labs",
"version": "1.0.0",
"category": "development"
},
"description": "Systematic refactoring techniques, code smell elimination, pattern extraction, and legacy modernization"
}
Refactoring Patterns
Systematically improve code without changing its behavior.
The Refactoring Workflow
- Identify a code smell or pain point
- Ensure you have tests (write them first if not)
- Apply one refactoring at a time
- Test after each change (green = continue, red = revert)
- Commit — small, focused, descriptive
- Repeat
Extract Method
When: A method does multiple things or is too long. How: Find a cohesive block → extract to new method → call it.
// Before
function processOrder(order) {
const total = order.items.reduce((sum, i) => sum + i.price, 0);
const tax = total * 0.08;
const discount = order.coupon ? total * 0.1 : 0;
return total + tax - discount;
}
// After
function processOrder(order) {
const subtotal = calculateSubtotal(order);
const tax = calculateTax(subtotal);
const discount = calculateDiscount(order, subtotal);
return subtotal + tax - discount;
}
Replace Conditional with Polymorphism
When: Switch/if-else chains based on type grow too long.
// Before
function calculateShipping(order) {
if (order.type === 'standard') return order.weight * 0.5;
if (order.type === 'express') return order.weight * 1.5 + 5;
if (order.type === 'overnight') return order.weight * 3 + 15;
}
// After
class StandardShipping {
calculate(weight) { return weight * 0.5; }
}
class ExpressShipping {
calculate(weight) { return weight * 1.5 + 5; }
}
Legacy Code Strategy
- Characterize with tests: Write tests that capture current behavior
- Sprout method: Add new code in new methods, don't modify old
- Wrap method: Wrap entire methods with new behavior (logging, caching)
- Step-by-step: Extract small pieces over time
- Strangler pattern: New code replaces old incrementally, old gets retired
Common Refactorings
| Refactoring | When | Risk |
|---|---|---|
| Rename Variable | Unclear name | Low |
| Extract Method | Long function | Low |
| Replace Magic Literal | Hard-coded values | Low |
| Introduce Parameter Object | Many parameters | Medium |
| Replace Temp with Query | Reused expressions | Low |
| Decompose Conditional | Complex condition | Medium |
| Extract Class | Class doing too much | Medium-High |
Version History
- 38e2523 Current 2026-07-05 19:38


