Refactoring Safely
БесплатноБез исполняемых скриптовНе проверенRefactor with tests first, one change at a time, never mix refactoring with bug fixes or new features
Об этом скилле
Refactoring Safely
Overview
Refactoring means changing code structure without changing behavior. Safe refactoring requires tests first, one change at a time, and NEVER mixing refactoring with bug fixes or features.
Core principle: Refactoring changes HOW code works internally. Bug fixes change WHAT code does. Never mix HOW and WHAT changes.
Violating the letter of this rule is violating the spirit of safe refactoring.
When to Use
Use before any refactoring:
- Improving names
- Extracting methods/classes
- Reducing complexity
- Improving structure
- Code review feedback
Critical moments:
- When you discover a bug during refactoring
- When tempted to "add this feature while I'm here"
- When making multiple structural changes
- When refactoring without tests
The Iron Laws of Safe Refactoring
LAW 1: TESTS BEFORE REFACTORING (NO EXCEPTIONS)
LAW 2: ONE CHANGE AT A TIME
LAW 3: NEVER MIX REFACTORING WITH BUG FIXES OR FEATURES
Violating any law makes refactoring unsafe.
Law 1: Tests Before Refactoring
Before refactoring ANY code, you MUST have passing tests.
No exceptions:
- Don't refactor "and add tests after"
- Don't "manually verify" instead of automated tests
- Don't "trust that it works"
- Don't refactor untested code without adding tests first
Process:
- If tests exist and pass: Proceed with refactoring
- If tests exist but fail: Fix tests first, THEN refactor
- If no tests exist: STOP. Add tests. Watch them pass. THEN refactor.
❌ Without tests (from baseline):
# Refactor immediately
def calc(x, y, z): # Bad names
...
# Refactor to:
def calculate_capped_product(first, second, multiplier):
...
# Hope it still works!
✅ With tests first:
# Step 1: Add tests
def test_calc():
assert calc(2, 3, 4) == 20
assert calc(10, 20, 5) == 100 # Capped
# Run - ALL PASS
# Step 2: Refactor
def calculate_capped_product(first, second, multiplier):
sum_of_addends = first + second
uncapped = sum_of_addends * multiplier
return min(uncapped, 100)
# Step 3: Run tests again - VERIFY STILL PASS
Tests prove refactoring didn't break behavior.
Law 2: One Change at a Time
Make ONE structural change. Test. Commit. Repeat.
Don't:
- Extract 6 methods simultaneously
- Rename variables AND extract methods together
- Change structure AND algorithms together
Do:
- Extract method A. Test. Commit.
- Extract method B. Test. Commit.
- Rename variable X. Test. Commit.
❌ Multiple changes (risky):
# Change 1: Extract validation
# Change 2: Extract calculation
# Change 3: Extract persistence
# Change 4: Rename variables
# Change 5: Reorder statements
# Change 6: Add error handling
# If tests fail: which change broke it?
✅ Incremental (safe):
# Change 1: Extract validation
def validate_order(data):
...
# Run tests → PASS → Commit
# Change 2: Extract calculation
def calculate_total(items):
...
# Run tests → PASS → Commit
# If any test fails: know exactly which change broke it
From baseline: Agent chose incremental approach correctly. Skill reinforces this.
Law 3: Never Mix Refactoring with Bug Fixes
This is the critical discipline most developers violate.
Refactoring = change structure, preserve behavior Bug fix = change behavior to correct it
Never do both in the same commit.
The Temptation (From Baseline Test 3)
You're refactoring and discover a bug:
# Extracting validation from larger function
def validate_order_items(order_data):
if not order_data.get('items'):
return None # ← BUG: should raise error
Tempting reasoning:
- "I'm touching this code anyway"
- "It's a trivial fix"
- "Efficient to fix while I'm here"
- "One coherent change"
Why this is WRONG:
Diagnosis confusion: If tests fail after your commit, is it because:
- Refactoring broke something?
- Bug fix was wrong?
- Impossible to tell when mixed
Review confusion: Reviewer must evaluate:
- Is the refactoring good?
- Is the bug fix correct?
- Mixed changes are harder to review
Revert problems: If bug fix is wrong, reverting loses good refactoring
Violates single-change principle: One commit = one purpose
The Correct Approach
When you discover a bug during refactoring:
STOP refactoring immediately
STASH or commit refactoring work-in-progress
FIX the bug:
- Write failing test for bug
- Fix bug
- Verify test passes
- Commit bug fix separately
UNSTASH and continue refactoring
Concrete example:
# You're refactoring, discover bug
git stash # Save refactoring work
# Fix bug in separate commit
# 1. Write test
def test_empty_items_raises_error():
with pytest.raises(ValueError):
validate_order_items({'items': []})
# Run - FAILS (bug exposed)
# 2. Fix bug
def validate_order_items(order_data):
if not order_d
Установить Refactoring Safely в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Refactoring Safely?
Refactor with tests first, one change at a time, never mix refactoring with bug fixes or new features
Как установить скилл Refactoring Safely?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Refactoring Safely запускает скрипты?
Нет, скилл состоит только из инструкций (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