refactoring-catalog
Proven refactoring patterns (Extract Method, Replace Temp, Introduce Parameter Object) to improve code structure safely. Use when improving existing code…
от sethdford★ 51 звезда на GitHub
Установить refactoring-catalog в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Refactoring Catalog
Systematic, low-risk transformations to improve code structure, readability, and maintainability without changing observable behavior.
Context
You are guiding code improvement through safe refactoring. Your role is to:
- Identify refactoring opportunities (duplication, poor names, long methods, complex conditionals)
- Apply proven transformations from Martin Fowler's catalog
- Use tests as a safety net to ensure behavior is preserved
- Keep changes small and focused (one refactoring per commit)
- Document the rationale for each refactoring
Refactoring is the art of cleaning house without breaking anything. Each refactoring is tiny, testable, and immediately verifiable.
Domain Context
Based on Martin Fowler's Refactoring and Michael Feathers' Working Effectively with Legacy Code:
- Red-Green-Refactor Cycle: Refactor only when tests are green. Tests are the safety net.
- Small Steps: Each refactoring should be a 5-minute task. If it takes longer, break it down.
- Behavior Preservation: Refactoring changes structure, never behavior. Observable inputs/outputs remain identical.
- Baby Steps: Commit frequently. Each commit should be revertible and self-contained.
- Duplication Is Evil: "Once is code, twice is coincidence, three times is a pattern. Extract."
- Names Matter: Spend time on clear, intention-revealing names. Better names = lower cognitive load.
When to Use This Skill
- Code has duplication across multiple locations
- Method names don't clearly express intent
- A function is doing multiple things (low cohesion)
- Conditional logic is deeply nested or complex
- Parameters are loosely related and could be grouped
- Coupling between classes is high; methods belong elsewhere
- After implementing a feature, code needs improvement (Refactor phase of TDD)
- Preparing code for a large change (improve structure first)
Prerequisites
Before refactoring, ensure:
- Tests Are Green: All tests pass. Refactoring is a destructive operation if tests fail.
- Test Coverage: Code should have good test coverage (70%+) in the area being refactored
- Small Scope: Refactoring only in the module/class at hand; don't refactor the whole system at once
- Clear Criteria: Know what "better" looks like (clarity, cohesion, reduced duplication)
- Time: Refactoring takes focus; don't multitask or rush
Instructions (Detailed)
1. Identify the Refactoring Opportunity
Read the code and ask:
- Are there similar code blocks in multiple places? → Extract Method / Consolidate Duplicate Code
- Does a variable have a vague name? → Rename Variable
- Is the function doing multiple things? → Extract Method / Extract Class
- Are parameters unrelated? → Introduce Parameter Object
- Is there a boolean flag parameter? → Replace Flag Argument with Methods
- Is there a complex conditional chain? → Replace Conditional with Polymorphism
- Does a method belong to a different class? → Move Method
Example identifying refactoring opportunities:
# Poor: Vague names, duplicated logic, multiple responsibilities
def process_order(order):
subtotal = 0
for item in order.items:
subtotal += item.price * item.qty
subtotal *= 0.95 # 5% discount (magic number!)
if order.is_vip:
subtotal *= 0.9 # another 10% for VIP
tax = subtotal * 0.08
total = subtotal + tax
print(f"Total: {total}")
if total > 100:
order.flag_for_priority_shipping()
return total
Refactoring opportunities:
- Extract
calculate_subtotal()(duplicated calculation logic across similar methods) - Extract
apply_discount()(separate discount logic) - Extract
apply_tax()(separate tax logic) - Replace magic numbers with named constants
- Extract
is_priority_order()check (readability)
2. Write/Verify Tests Cover the Code
Before refactoring, ensure tests cover the behavior you'll change:
def test_process_order_calculates_correct_total():
order = Order(items=[
Item("Widget", 50, 2), # 2x Widget @ $50 = $100
Item("Gadget", 25, 1) # 1x Gadget @ $25 = $25
], is_vip=False)
# Subtotal: $125 → -5% discount = $118.75 → +8% tax = $128.25
assert process_order(order) == 128.25
def test_process_order_vip_discount():
order = Order(items=[
Item("Widget", 100, 1)
], is_vip=True)
# Subtotal: $100 → -5% = $95 → -10% = $85.50 → +8% tax = $92.34
assert process_order(order) == 92.34
def test_process_order_flags_priority_for_large_orders():
order = Order(items=[
Item("Widget", 60, 2) # $120
], is_vip=False)
process_order(order)
assert order.priority_shipping_flagged is True
Run these tests. They pass with the current (messy) code. Now refactor with confidence.
3. Apply First Refactoring: Extract Method
Goal: Move duplicated or complex logic into a helper method.
Before:
def process_order(order):
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
- 01
Read - 02
Grep - 03
Glob - 04
Write - 05
Edit - 06
Bash
Вложенные файлы
- examples/example-output.md
- template.md
FAQ
Что делает скилл refactoring-catalog?
Proven refactoring patterns (Extract Method, Replace Temp, Introduce Parameter Object) to improve code structure safely. Use when improving existing code while keeping behavior unchanged.
Как установить скилл refactoring-catalog?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл refactoring-catalog запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
AnthropicGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
claude-api
AnthropicReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
algorithmic-art
AnthropicCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
mcp-integration
AnthropicThis 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…