Refactoring Safely
FreeNo executable scriptsNot checkedRefactor with tests first, one change at a time, never mix refactoring with bug fixes or new features
About this skill
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
Install Refactoring Safely in Claude Code & Claude Desktop
Sign up to install this skill
Create a free account to reveal the install command and save the skill to your library.
- Reveal the one-line install command
- Save skills to your synced library
- Get notified when skills update
Allowed tools
Tools this skill is permitted to call.
No restriction — this skill can use any tool.
FAQ
What does the Refactoring Safely skill do?
Refactor with tests first, one change at a time, never mix refactoring with bug fixes or new features
How do I install the Refactoring Safely skill?
Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.
Does the Refactoring Safely skill run scripts?
No, this skill is instructions only (SKILL.md) with no executable scripts.
Related skills
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…
by Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
by Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
by 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…
by Anthropic