refactor
БесплатноБез исполняемых скриптовНе проверенRestructure code to improve quality without changing behavior
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
Refactoring Skill
Improve code structure and quality while preserving behavior.
Name
han-core:refactor - Restructure code to improve quality without changing behavior
Synopsis
/refactor [arguments]
Core Principle
Tests are your safety net. Never refactor without tests.
The Refactoring Cycle
- Ensure tests exist and pass
- Make ONE small change
- Run tests (must still pass)
- Commit (keep changes isolated)
- Repeat
Each step must be reversible. If tests fail, revert and try smaller change.
Pre-Refactoring Checklist
STOP if any of these are false:
- Tests exist for code being refactored
- All tests currently pass
- Understand what code does
- External behavior will remain unchanged
- Have time to do this properly (not rushing)
If no tests exist:
- Add tests first
- Verify tests pass
- THEN refactor
When to Refactor
Code Smells That Suggest Refactoring
Readability issues:
- Long functions (> 50 lines)
- Deep nesting (> 3 levels)
- Unclear naming
- Magic numbers
- Complex conditionals
Maintainability issues:
- Duplication (same code in multiple places)
- God classes (too many responsibilities)
- Feature envy (method uses another class more than its own)
- Data clumps (same groups of parameters passed around)
Complexity issues:
- Cyclomatic complexity > 10
- Too many dependencies
- Tightly coupled code
- Difficult to test
When NOT to Refactor
- No tests exist (add tests first)
- Under deadline pressure (defer to later)
- Code works and is readable (don't over-engineer)
- Changing external behavior (that's not refactoring, that's a feature/fix)
- Right before release (too risky)
Classic Refactorings
Extract Function
Problem: Function does too many things
// Before: Long function doing multiple things
function processOrder(order: Order) {
// Validate order
if (!order.items || order.items.length === 0) {
throw new Error('Empty order')
}
if (!order.customer || !order.customer.email) {
throw new Error('Invalid customer')
}
// Calculate totals
let subtotal = 0
for (const item of order.items) {
subtotal += item.price * item.quantity
}
const tax = subtotal * 0.08
const shipping = subtotal > 50 ? 0 : 9.99
const total = subtotal + tax + shipping
// Save to database
return database.save({
...order,
subtotal,
tax,
shipping,
total
})
}
// After: Extracted into focused functions
function processOrder(order: Order) {
validateOrder(order)
const totals = calculateTotals(order)
return saveOrder(order, totals)
}
function validateOrder(order: Order): void {
if (!order.items || order.items.length === 0) {
throw new Error('Empty order')
}
if (!order.customer || !order.customer.email) {
throw new Error('Invalid customer')
}
}
function calculateTotals(order: Order) {
const subtotal = order.items.reduce(
(sum, item) => sum + item.price * item.quantity,
0
)
const tax = subtotal * 0.08
const shipping = subtotal > 50 ? 0 : 9.99
const total = subtotal + tax + shipping
return { subtotal, tax, shipping, total }
}
function saveOrder(order: Order, totals: Totals) {
return database.save({ ...order, ...totals })
}
Benefits: Each function has single responsibility, easier to test, easier to understand
Extract Variable
Problem: Complex expression that's hard to understand
// Before: Dense, hard to parse
if (user.age >= 18 && user.country === 'US' && !user.banned && user.verified) {
// ...
}
// After: Intent is clear
const isAdult = user.age >= 18
const isUSResident = user.country === 'US'
const hasGoodStanding = !user.banned && user.verified
const canPurchase = isAdult && isUSResident && hasGoodStanding
if (canPurchase) {
// ...
}
Benefits: Self-documenting, easier to debug, easier to modify
Inline Function/Variable
Problem: Unnecessary indirection that doesn't add clarity
// Before: Over-abstraction
function getTotal(order: Order) {
return calculateTotalAmount(order)
}
function calculateTotalAmount(order: Order) {
return order.subtotal + order.tax
}
// After: Inline the unnecessary layer
function getTotal(order: Order) {
return order.subtotal + order.tax
}
When to inline: Abstraction doesn't add value, makes code harder to follow
Rename
Problem: Unclear or misleading names
// Before: Unclear
function proc(d: any) {
const r = d.x * d.y
return r
}
// After: Self-explanatory
function calculateArea(dimensions: Dimensions) {
const area = dimensions.width * dimensions.height
return area
}
Benefits: Code is self-documenting, no need to guess what variables mean
Replace Magic Number with Named Constant
Problem: Unexplained numbers in code
// Before: What's 0.08? What's 9.99?
const tax = subtotal * 0.08
con
Установить refactor в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditBashGrepGlobFAQ
Что делает скилл refactor?
Restructure code to improve quality without changing behavior
Как установить скилл refactor?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл refactor запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic