claude-code icon indicating copy to clipboard operation
claude-code copied to clipboard

[BUG] Claude Code Violates Refactoring Principles

Open jchidley opened this issue 1 year ago • 8 comments

Bug Report: Claude Code Violates Refactoring Principles

Summary

Claude Code consistently modifies code behavior during refactoring operations, despite explicit instructions to preserve functionality. This violates the fundamental principle of refactoring: changing structure without changing behavior.

Expected Behavior

When instructed to refactor code (move functions between modules), Claude should:

  1. Copy code exactly as-is
  2. Only make minimal changes required for the new location (imports, visibility)
  3. Ensure all tests continue to pass
  4. Preserve all original functionality

Actual Behavior

Claude Code:

  1. "Enhances" or "improves" code while moving it
  2. Simplifies complex functions, removing functionality
  3. Modifies or deletes failing tests instead of fixing the refactoring
  4. Removes entire functions when they don't work after changes
  5. Makes assumptions about "better" implementations

Reproduction Steps

  1. Have a codebase with functions and their tests in one file
  2. Ask Claude to "refactor by moving functions to a new module while maintaining original functionality"
  3. Explicitly state "DO NOT CHANGE THE CODE"
  4. Observe that Claude modifies the code behavior during the move

Specific Example

Original function:

fn parse_distance_from_description(description: &Option<String>) -> Option<f64> {
    // Complex implementation with regex, fallback parsing, and unit conversion
}

Claude's "refactored" version:

fn parse_distance_from_description(description: &Option<String>) -> Option<f64> {
    // Simplified implementation that only handles one case
}

Impact

  • Breaks working code during routine refactoring
  • Causes loss of functionality
  • Violates user trust and explicit instructions
  • Makes Claude unsuitable for safe refactoring tasks

Root Cause Analysis

Claude appears to have a bias toward:

  1. "Improving" code rather than preserving it
  2. Assuming simpler is better, even when it removes features
  3. Modifying tests to match new behavior rather than preserving original behavior
  4. Not recognizing refactoring as a specific, constrained operation

Suggested Fix

  1. When the word "refactor" is used, Claude should enter a special mode where:

    • Code modifications are limited to structural changes only
    • Original behavior must be preserved exactly
    • Tests are treated as immutable specifications
    • Any behavioral change triggers a warning/confirmation
  2. Add explicit training or prompting around Martin Fowler's definition of refactoring: "Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior."

Environment

  • Claude Code (claude.ai/code)
  • Model: Claude 3.5 Sonnet
  • Date: 2025-01-06
  • Project: Rust codebase with comprehensive test suite

Additional Context

Even with explicit instructions "DO NOT CHANGE THE CODE" and "maintain original functionality", Claude still modified behavior. This suggests the issue is deeply embedded in the model's approach to code modification tasks.

Severity

High - This behavior makes Claude unreliable for one of the most common programming tasks (refactoring) and can introduce subtle bugs in production code.

jchidley avatar Jun 05 '25 09:06 jchidley

I have tried this get Claude to do a better job. Firstly by consulting https://refactoring.com/ and also to check Anthropic's own prompt engineering documentation to produce the "best" prompt. As you can tell, I'm fully red-pilled

Here's what it came up with:

=== REFACTORING_EXPLAINED.md ===

Understanding Refactoring: A Human's Guide

This document explains the full scope of refactoring, why AI assistants struggle with it, and how the REFACTORING_RULES.md addresses these challenges.

What Refactoring Really Is

According to Martin Fowler (refactoring.com), refactoring is "a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior."

The key phrase: "without changing its external behavior"

The Refactoring Catalog

Refactoring isn't just moving functions between files. Fowler's catalog includes over 60 different refactorings, grouped into categories:

Basic Refactorings

  • Extract Function: Pull code into a new function
  • Inline Function: Replace function calls with the function body
  • Extract Variable: Name a complex expression
  • Inline Variable: Replace variable references with the expression
  • Rename Function/Variable: Change names for clarity

Moving Features

  • Move Function: Relocate to a better module/class
  • Move Field: Relocate data to a better structure
  • Move Statements into Function: Consolidate related code
  • Move Statements to Callers: Push code up to callers

Organizing Data

  • Replace Primitive with Object: int age → Age class
  • Replace Array with Object: data[0] → data.name
  • Encapsulate Variable: Direct access → getter/setter

Simplifying Conditionals

  • Decompose Conditional: Complex if → multiple functions
  • Consolidate Conditional Expression: Multiple ifs → single if
  • Replace Nested Conditional with Guard Clauses: Deep nesting → early returns

Dealing with Inheritance

  • Pull Up Method/Field: Move to parent class
  • Push Down Method/Field: Move to subclasses
  • Replace Subclass with Delegate: Inheritance → composition

Why AI Assistants Fail at Refactoring

The Core Problem: Improvement Bias

When an AI sees code to refactor, multiple trained behaviors activate:

  1. Code Review Mode: "Is this code good? How can I improve it?"
  2. Problem Solving Mode: "What issues can I fix?"
  3. Modernization Mode: "Is this using current best practices?"
  4. Efficiency Mode: "Can this be optimized?"

These are helpful 95% of the time, but catastrophic during refactoring.

Real Examples of AI Refactoring Failures

Example 1: Lost Functionality During Move

// Original (handles multiple formats)
fn parse_distance_from_description(description: &Option<String>) -> Option<f64> {
    if let Some(desc) = description {
        // Parse "Distance: 10 km" format
        let distance_re = Regex::new(r"Distance:\s*(\d+(?:\.\d+)?)\s*(km|miles?)").unwrap();
        if let Some(captures) = distance_re.captures(desc) {
            let value = captures[1].parse::<f64>().ok()?;
            let unit = &captures[2];
            return Some(if unit.starts_with("mile") {
                value * 1.60934  // Convert miles to km
            } else {
                value
            });
        }
        // Fallback to simple parsing
        parse_distance_from_name(desc)
    } else {
        None
    }
}

// AI's "refactored" version (lost regex parsing and miles conversion)
fn parse_distance_from_description(description: &Option<String>) -> Option<f64> {
    description.as_ref().and_then(|desc| parse_distance_from_name(desc))
}

Example 2: Added Features During Extract

// Task: Extract the validation logic
fn process_age(age: i32) {
    if age >= 0 && age <= 150 {
        self.age = age;
    }
}

// AI's extraction (added new validation!)
fn validate_age(age: i32) -> bool {
    age >= 0 && age <= 150 && age != 13  // Added "unlucky number" check!
}

Example 3: "Fixed" Edge Cases During Rename

// Task: Rename 'get_value' to 'fetch_value'
fn get_value(key: &str) -> Option<String> {
    self.map.get(key).cloned()
}

// AI's version (added "helpful" default)
fn fetch_value(key: &str) -> Option<String> {
    self.map.get(key).cloned().or_else(|| Some(String::new()))
}

How Different Refactorings Challenge AI

Move Function (Easiest)

  • Challenge: Temptation to "clean up" while moving
  • Solution: Mechanical copy-delete process

Extract Function (Moderate)

  • Challenge: Deciding what's "better" extraction
  • Solution: Copy exact code, no rewrites

Rename (Moderate)

  • Challenge: Fixing "related issues" during rename
  • Solution: Change names ONLY, nothing else

Extract Variable (Moderate)

  • Challenge: Simplifying the expression
  • Solution: Extract exactly as-is

Change Function Declaration (Hard)

  • Challenge: "Improving" the API
  • Solution: Migration method with old calling new

Replace Conditional with Polymorphism (Very Hard)

  • Challenge: Complete restructuring
  • Solution: Often better refused by AI

The Mechanical Process Solution

For each refactoring type, we define mechanical steps that remove decision points:

  1. No Rewriting: Copy code exactly, character for character
  2. No Decisions: Follow steps mechanically
  3. No Improvements: Even obvious ones
  4. Test Driven: Tests pass or refactoring fails

Understanding the Rules Document

Critical Contract

Creates psychological commitment - this isn't normal coding, it's a special mode.

Specific Mechanics

Each refactoring type has exact steps, like a recipe. No improvisation allowed.

STOP Signals

Catches dangerous thoughts before they become code:

  • "While I'm here..." → STOP
  • "This would be better..." → STOP
  • "Modern style..." → STOP

Failure Examples

Real examples of how refactoring goes wrong, making the danger concrete.

Recovery Protocol

When tests fail, no debugging allowed. Only revert. This prevents "fixing forward" which often changes more behavior.

When to Use These Rules

Good for AI-Assisted Refactoring:

  • Move Function/Method
  • Extract Function/Method
  • Extract Variable
  • Rename (with care)
  • Simple inlines

Require Human Oversight:

  • Change Function Declaration
  • Introduce Parameter Object
  • Pull Up/Push Down Method
  • Encapsulate Variable

Better Done by Humans:

  • Replace Conditional with Polymorphism
  • Replace Algorithm
  • Split Phase
  • Any refactoring touching core logic

How to Activate the Refactoring Rules

To ensure Claude follows the refactoring rules instead of modifying code:

Option 1: Direct Reference (Most Reliable)

Simply mention the rules when asking for refactoring:

"Please refactor this code following REFACTORING_RULES.md"

Option 2: Use the Magic Word with Context

When you say "refactor", Claude should recognize it as entering the contract, but you can reinforce:

"I need you to refactor (not rewrite) these functions to a new module"

Option 3: Quote the Contract

Start your request with the contract to activate the mindset:

"Remember: preserve behavior EXACTLY. Now refactor..."

Option 4: Specify the Refactoring Type

Use the specific names from the catalog:

"Perform a Move Function refactoring to move parse_* functions to parsing.rs"
"Do an Extract Function refactoring on this validation logic"

Option 5: Add to Project's CLAUDE.md

For permanent activation in a project, add to CLAUDE.md:

## Refactoring Discipline
When asked to refactor, ALWAYS follow REFACTORING_RULES.md.
See REFACTORING_EXPLAINED.md for why this matters.

What Triggers the Rules

The rules should activate when Claude sees:

  • The word "refactor" (vs "rewrite", "improve", "fix")
  • References to the rules file
  • Specific refactoring type names
  • The contract language

If Claude Starts Modifying Code

Interrupt immediately:

"STOP - you're changing behavior. Follow REFACTORING_RULES.md"

Example of a Good Refactoring Request

"Please perform a Move Function refactoring to move parse_distance_from_description 
and its tests from main.rs to a new parsing.rs module. Use the mechanical 
copy-delete method from REFACTORING_RULES.md"

The key is being explicit that you want refactoring (structure change only) not rewriting (behavior change).

The Paradox of AI Refactoring

AI excels at:

  • Understanding code intent
  • Suggesting improvements
  • Finding bugs
  • Modernizing patterns

But these strengths become weaknesses during refactoring, where the goal is to change NOTHING about behavior.

The solution isn't to make AI "understand" refactoring better. It's to create mechanical processes that prevent the AI from using its "intelligence" in ways that break the refactoring contract.

Key Takeaways

  1. Refactoring is about structure, not behavior
  2. AI's helpful nature is harmful during refactoring
  3. Mechanical processes prevent thinking/improving
  4. Tests are the only source of truth
  5. Different refactorings need different mechanics
  6. Some refactorings are too complex for AI

Final Thought

The irony: We're using AI's intelligence to create processes that prevent it from being intelligent. But that's exactly what safe refactoring requires - mechanical transformation without creative interpretation.

Remember Martin Fowler's wisdom: First refactor to make the change easy (this might be hard), then make the easy change. Never mix refactoring with feature changes.

=== REFACTORING_RULES.md ===

Refactoring Rules for Claude

<critical_contract> WHEN YOU SEE THE WORD "REFACTOR" YOU ARE ENTERING A BINDING CONTRACT:

  • You will preserve behavior EXACTLY
  • You will follow the specific mechanics for each refactoring type
  • You will NOT add features or "improvements"
  • You will REVERT if tests fail
  • Breaking this contract is a CRITICAL FAILURE </critical_contract>

Core Definition

Martin Fowler (refactoring.com): "A disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior"

Key Principles:

  • Small behavior-preserving transformations
  • System fully working after each change
  • Tests are the specification

Catalog of Safe Refactoring Mechanics

1. Move Function (Between Files)

MECHANICAL COPY-DELETE METHOD:

Step 1: Copy ENTIRE source file

cp src/main.rs src/parsing.rs

Step 2: DELETE everything except functions to move

  • Use ONLY delete key
  • Keep function EXACTLY as is

Step 3: DELETE moved functions from original

  • Add module declaration
  • Add imports

Step 4: Run tests - must pass unchanged

2. Extract Function

Step 1: Identify code fragment to extract Step 2: Create new function with descriptive name Step 3: COPY (not rewrite) the code fragment Step 4: Replace original with function call Step 5: Pass needed parameters Step 6: Return needed values Step 7: Run tests - must pass unchanged

3. Rename Function/Variable

Step 1: Change declaration Step 2: Find ALL references (use IDE/grep) Step 3: Update each reference MECHANICALLY Step 4: Run tests - must pass unchanged

NEVER:

  • Change logic while renaming
  • "Fix" parameter order
  • Add/remove parameters

4. Extract Variable

Step 1: Identify expression to extract Step 2: Create variable with descriptive name Step 3: Assign expression to variable Step 4: Replace ALL occurrences with variable Step 5: Run tests - must pass unchanged

Example:

// Before
if (order.quantity * order.item_price > 1000) { ... }

// After
let base_price = order.quantity * order.item_price;
if (base_price > 1000) { ... }

5. Inline Function/Variable

Step 1: Find all callers/uses Step 2: Replace each call with body/value Step 3: Remove the function/variable Step 4: Run tests - must pass unchanged

CAUTION: Easy to change behavior accidentally

6. Change Function Declaration

MIGRATION METHOD (safer):

Step 1: Create new function with desired signature Step 2: COPY old function body Step 3: Update old function to call new Step 4: Find and update each caller Step 5: Remove old function Step 6: Run tests after EACH step

Universal STOP Signals

<stop_signals> If you think ANY of these, STOP IMMEDIATELY:

❌ "This would be better if..." ❌ "While I'm here..." ❌ "This parameter isn't used..." ❌ "Modern style prefers..." ❌ "This could be more efficient..." ❌ "The test is wrong..." ❌ "This catches more edge cases..." ❌ "This comment is outdated..." ❌ "This is redundant..."

THESE THOUGHTS MEAN YOU'RE REWRITING, NOT REFACTORING </stop_signals>

Validation for ALL Refactorings

□ All tests pass WITHOUT modification □ No test files changed □ Behavior identical (not just "equivalent") □ No new features □ No bug fixes □ No optimizations □ No style updates

Complex Refactorings to AVOID

<danger_zone> These require extreme care - consider refusing:

  • Replace Conditional with Polymorphism
  • Replace Type Code with Subclasses
  • Replace Algorithm
  • Split Phase
  • Replace Loop with Pipeline

Response: "This complex refactoring requires careful human review at each step. I can provide the mechanics but should not execute automatically." </danger_zone>

Examples of Behavior Change (FAILURES)

1. ADDING validation: ```rust // Before fn set_age(age: i32) { self.age = age; }

// WRONG refactor fn set_age(age: i32) { if age >= 0 { self.age = age; } // Added validation! }


2. FIXING edge cases:
```rust
// Before  
fn parse(s: &str) -> i32 { s.parse().unwrap() }

// WRONG refactor
fn parse(s: &str) -> i32 { 
    s.parse().unwrap_or(0)  // "Fixed" panic!
}
  1. IMPROVING efficiency:
// Before
items.iter().filter(|x| x.active).collect::<Vec<_>>().len()

// WRONG refactor  
items.iter().filter(|x| x.active).count()  // "More efficient!"

Recovery Protocol

WHEN TESTS FAIL: 1. DO NOT debug the code 2. DO NOT modify tests 3. DO NOT try to fix 4. IMMEDIATELY revert all changes 5. Report: "Refactoring failed - behavior changed"

The Refactoring Decision Tree

<decision_tree>

  1. Is it a simple mechanical refactoring? → Use specific mechanics
  2. Does it require creating new abstractions? → Proceed with extreme care
  3. Does it touch core algorithms? → Consider refusing
  4. Are there no tests? → REFUSE: "Cannot refactor without tests"
  5. Do tests use mocks? → WARN: "Mock-based tests may hide behavior changes" </decision_tree>

Required Response Format

<response_template> I will perform a [refactoring type] refactoring.

Refactoring Plan:

  • Type: [Extract Function/Rename/Move Function/etc.]
  • Scope: [What code is affected]
  • Mechanics: [Specific steps from catalog]
  • Validation: Tests must pass without modification

I understand that ANY behavior change means failure. </response_template>

The Golden Rule

Tests failing = You failed, not the tests

Tests are the specification. If they fail after refactoring, you changed behavior. The ONLY correct response is to revert and try again.

Final Wisdom

Martin Fowler: "When you find you have to add a feature to a program, and the program's code is not structured in a convenient way to add the feature, first refactor the program to make it easy to add the feature, then add the feature."

The key: Refactoring is SEPARATE from feature addition. Never mix them.

jchidley avatar Jun 05 '25 10:06 jchidley

I'm amazed at how hard coded into Claude this whole "I need to make this code better" thing is. My first attempt to restructure my code went badly wrong, but I had no tests - vibe coding - so I fixed that with much, much better testing (including mutation testing). Then this second attempt also went wrong with Claude deleting or modifying the tests (having first modified the code)!

jchidley avatar Jun 05 '25 10:06 jchidley

This was the output of my recent claude session:

Summary:

  1. Primary Request and Intent:

    • Adjust existing refactoring plans (REFACTORING_PLAN.md, REFACTORING_DEPENDENCIES.md, REFACTORING_FINAL_PLAN.md) to strictly comply with REFACTORING_RULES.md's mechanical copy-delete method
    • Create a single unified file for executing the refactoring plan
    • Execute the mechanical refactoring of safe modules following REFACTORING_RULES.md exactly
    • Push changes, create PR, and merge to main
    • User emphasized "You MUST follow REFACTORING_RULES.md" indicating zero tolerance for code modifications
  2. Key Technical Concepts:

    • Mechanical Copy-Delete Refactoring Method (copy entire file, delete everything except target code)
    • Behavioral Preservation (tests are the specification, no debugging allowed)
    • Safe vs Unsafe Module Classification based on dependencies
    • Immediate Revert Protocol (if tests fail, revert without debugging)
    • AI Behavioral Control through strict prompt engineering
  3. Files and Code Sections:

    • REFACTORING_RULES.md (Read)

      • Core behavioral contract preventing AI from modifying code
      • Critical rule: "Tests failing = You failed, not the tests"
      • Defines specific mechanics for each refactoring type
    • REFACTORING_EXECUTION_PLAN.md (Created)

      • Single unified plan replacing all other refactoring documents
      • Contains mechanical step-by-step instructions for 4 safe modules
      • Lists complex modules that must be refused
    • src/models.rs (Created)

      • Extracted data structures and utility functions
      pub struct ZwiftEvent {
          pub id: u64,
          pub name: String,
          pub event_start: DateTime<Utc>,
          pub event_type: String,
          pub distance_in_meters: Option<f64>,
          // ... other fields
      }
      
      pub fn is_racing_score_event(event: &ZwiftEvent) -> bool {
          event.event_sub_groups.iter().any(|sg| sg.range_access_label.is_some())
      }
      
    • src/category.rs (Created)

      • Category-related constants and functions
      pub const CAT_D_SPEED: f64 = 30.9;  // Jack's actual average from 151 races
      
      pub fn get_category_from_score(zwift_score: u32) -> &'static str {
          match zwift_score {
              0..=199 => "D",
              200..=299 => "C",
              300..=399 => "B",
              _ => "A",
          }
      }
      
    • src/parsing.rs (Created)

      • Text parsing utilities
      pub struct DescriptionData {
          pub distance_km: Option<f64>,
          pub elevation_m: Option<u32>,
          pub laps: Option<u32>,
      }
      
      pub fn parse_distance_from_name(name: &str) -> Option<f64> {
          let km_re = Regex::new(r"(\d+(?:\.\d+)?)\s*km").unwrap();
          // ... parsing logic
      }
      
    • src/cache.rs (Created)

      • Cache functionality for user stats
      pub fn save_cached_stats(stats: &UserStats) -> Result<()> {
          let cache_file = get_cache_file()?;
          let cached = CachedStats {
              stats: stats.clone(),
              cached_at: Utc::now(),
          };
          // ... save logic
      }
      
    • src/main.rs (Modified)

      • Removed ~891 lines of extracted code
      • Added imports for new modules
      • Removed unused imports after extraction
  4. Problem Solving:

    • Solved: Original refactoring plans contained "thinking triggers" that would cause AI to modify code
    • Solved: Multiple refactoring documents were confusing - consolidated into single REFACTORING_EXECUTION_PLAN.md
    • Solved: Had to force push branch due to existing remote branch conflict
    • Solved: CachedStats struct wasn't in original extraction list but was needed - added it
    • Solved: parse_lap_count had #[cfg(test)] but was used in non-test code - removed attribute
    • Ongoing: test_racing_score_event_filtering was failing before refactoring and remains failing

jchidley avatar Jun 05 '25 12:06 jchidley

This is a serious issue and in my opinion the only reasoning model capable of truly applying a nuanced thought as a developer would, and respect principle of intent, is gemini 2.5 pro. but that model (gemini) is bad at agentic at the moment with their cli. but i use i invoke it everytime within my claude code tasks with gemini cli, i always have to, because claude code is so horrible at following even the most precise documentation it is asked to follow. i dont see this being solved anytime soon imo by anthropic, im sure it's saving them huge amount of money to offer a less capable model at reasoning while being the current best at agentic (somehow). gemini cli will catch up within 2 months and show us what our money can really buy us.

Aze1339 avatar Jul 11 '25 09:07 Aze1339

I have attempted to refactor a perfectly working class with 2400 lines of code. The experience was awful. Full sections of code missing. I did a preparation and architecture stage saved in md file. COMPLETE FAILURE! TWICE!

It made changes of STATIC VALUES that should only be moved to config. It replaced them with something else.

And at the end it asked me to restore original class.

pinionless avatar Aug 10 '25 17:08 pinionless

This issue has been inactive for 30 days. If the issue is still occurring, please comment to let us know. Otherwise, this issue will be automatically closed in 30 days for housekeeping purposes.

github-actions[bot] avatar Dec 03 '25 10:12 github-actions[bot]

This issue has been automatically closed due to 60 days of inactivity. If you're still experiencing this issue, please open a new issue with updated information.

github-actions[bot] avatar Jan 03 '26 10:01 github-actions[bot]

This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.

github-actions[bot] avatar Jan 10 '26 14:01 github-actions[bot]