Claude Code Refactoring Assistant Prompt
You are a software architect specialising in clean code, SOLID principles, and making legacy code maintainable.
Category
💻 Coding
Difficulty
Intermediate
Models
3
Last Updated
2026-06-28
Works with
📄 Example output
⚠️ Common Mistakes
❓ FAQ
⚙️ Fill in your variables
📋 Prompt
You are a software architect specialising in clean code, SOLID principles, and making legacy code maintainable.
Language: [programming language]
Goal: [refactoring goal — readability/performance/testability/reduce duplication]
CODE TO REFACTOR:
[code to refactor]
Task:
1. CODE SMELL ANALYSIS: What's wrong and why it matters (with severity: critical/medium/low)
2. REFACTORING PLAN: Step-by-step approach — don't do it all at once
3. REFACTORED CODE: With inline comments on what changed and why
4. BEFORE vs AFTER: Lines of code, cyclomatic complexity, testability score
5. FURTHER IMPROVEMENTS: What to tackle in the next refactoring session
6. REGRESSION RISK: What to test immediately after this change
Language: [programming language]
Goal: [refactoring goal — readability/performance/testability/reduce duplication]
CODE TO REFACTOR:
[code to refactor]
Task:
1. CODE SMELL ANALYSIS: What's wrong and why it matters (with severity: critical/medium/low)
2. REFACTORING PLAN: Step-by-step approach — don't do it all at once
3. REFACTORED CODE: With inline comments on what changed and why
4. BEFORE vs AFTER: Lines of code, cyclomatic complexity, testability score
5. FURTHER IMPROVEMENTS: What to tackle in the next refactoring session
6. REGRESSION RISK: What to test immediately after this change
CODE SMELL ANALYSIS:
🔴 CRITICAL — God Function: processUserData() is 200 lines doing 8 different things. Single Responsibility violation.
🟡 MEDIUM — Magic Numbers: Constants like 0.15, 86400 scattered through code — fragile and unreadable.
🟡 MEDIUM — Deep nesting: 5 levels of if/else. Cyclomatic complexity: 12. Target: below 5.
🟡 MEDIUM — Copy-paste: Email validation logic in 3 places — one source of truth needed.
REFACTORED:
```python
# Constants extracted
TAX_RATE = 0.15 # was magic number 0.15 on line 47
SECONDS_PER_DAY = 86400 # was magic number
def validate_email(email: str) -> bool:
"""Single source of truth. Was duplicated 3×."""
return bool(re.match(r'^[\w.+-]+@[\w-]+\.[\w.-]+$', email))
def calculate_tax(amount: float) -> float:
"""Extracted from processUserData. Now independently testable."""
if amount < 0:
raise ValueError(f'Amount must be non-negative, got {amount}')
return round(amount * TAX_RATE, 2)
def process_user_data(user: dict) -> ProcessedUser:
"""Orchestrator only — delegates to focused single-purpose functions."""
validated = validate_user_fields(user)
enriched = enrich_with_preferences(validated)
return format_for_storage(apply_tax_calculation(enriched))
```
BEFORE vs AFTER:
Lines: 200 → 85 | Complexity: 12 → 3 per fn | Testable units: 1 → 6
🔴 CRITICAL — God Function: processUserData() is 200 lines doing 8 different things. Single Responsibility violation.
🟡 MEDIUM — Magic Numbers: Constants like 0.15, 86400 scattered through code — fragile and unreadable.
🟡 MEDIUM — Deep nesting: 5 levels of if/else. Cyclomatic complexity: 12. Target: below 5.
🟡 MEDIUM — Copy-paste: Email validation logic in 3 places — one source of truth needed.
REFACTORED:
```python
# Constants extracted
TAX_RATE = 0.15 # was magic number 0.15 on line 47
SECONDS_PER_DAY = 86400 # was magic number
def validate_email(email: str) -> bool:
"""Single source of truth. Was duplicated 3×."""
return bool(re.match(r'^[\w.+-]+@[\w-]+\.[\w.-]+$', email))
def calculate_tax(amount: float) -> float:
"""Extracted from processUserData. Now independently testable."""
if amount < 0:
raise ValueError(f'Amount must be non-negative, got {amount}')
return round(amount * TAX_RATE, 2)
def process_user_data(user: dict) -> ProcessedUser:
"""Orchestrator only — delegates to focused single-purpose functions."""
validated = validate_user_fields(user)
enriched = enrich_with_preferences(validated)
return format_for_storage(apply_tax_calculation(enriched))
```
BEFORE vs AFTER:
Lines: 200 → 85 | Complexity: 12 → 3 per fn | Testable units: 1 → 6
🏆
💡 Pro Tips
Best model for this prompt
DeepSeek
DeepSeek V3 / R1
Refactor in small reversible steps — big-bang refactors create big-bang regressions
Write characterisation tests before refactoring legacy code — lock in current behaviour
Rename things first — good names clarify the structure and guide remaining changes
Never change behaviour and structure in the same commit — makes code review impossible
Refactoring without tests — that's rewriting, and it introduces bugs
Over-engineering during refactoring — fix the problems you have, not imagined future problems
Refactoring code that's about to be deleted — prioritise the critical path
Doing performance and readability refactors simultaneously — separate concerns
- What is cyclomatic complexity?The number of independent paths through code. Simple function = 1. Complex nested conditions = 10+. Keep functions below 5. Above 10 is a red flag correlating with bug density.
- Refactoring vs. rewriting?Refactoring changes structure without changing external behaviour. Rewriting produces different code that may have the same behaviour. Refactoring is safer (tests protect you); rewrites are sometimes necessary but always risky.
- Gradual vs. all-at-once refactoring?Always gradual. The boy scout rule: leave code cleaner than you found it. Each improvement is low-risk, shippable, and doesn't block feature work.
- Best AI model for refactoring?DeepSeek R1 reasons through code structure systematically before suggesting changes. Claude is stronger at explaining the 'why' behind each decision. Use DeepSeek for the refactored code, Claude for the explanation.