Module 4: Coordinated Multi-File Refactoring

Module 4: Coordinated Multi-File Refactoring

Module 4: Coordinated Multi-File Refactoring

Capsule description

Phase 1 taught you to understand codebases: systematic onboarding, exploration with Explore, and complete architecture analysis. Now Phase 2 begins: modifying codebases. And the first type of modification — the most common and most valuable in your daily work — is refactoring: changing the structure of the code without changing its behavior.

What makes this module different from any refactoring tutorial is the word "coordinated." A rename in an IDE touches 3-4 files and takes 2 seconds. But a real refactoring — extract a service layer, reorganize the module structure, change an interface that 15 files consume — that's multi-file coordination. IDEs don't handle this well. Claude Code does: it can read all the affected files, understand the dependencies, and make the coordinated changes with verification.

This module has an implicit but fundamental prerequisite: guide #7 (Testing with Claude Code). Refactoring without tests is surgery without anesthesia — technically possible, but irresponsible. Before each refactoring, you write regression tests. After each refactoring, you verify that the tests pass. That cycle is the golden rule of this module.

By the end of the 6 capsules, you'll be able to plan and execute coordinated refactoring that touches multiple files, write regression tests before any change, and verify that the behavior was preserved — all by directing Claude Code as a coordinator, not as an autonomous generator.


Module Context

Where are we?

This is Guide #8 of the Claude Code Agentic Development Path, Phase 2: Refactoring (Modules 4-6).

Phase 1: Understand Codebases (Modules 1-3) ✅ COMPLETED
├── Module 1: Onboarding with AI ✅
├── Module 2: Agentic Research with Explore ✅
└── Module 3: Understand an Existing Architecture ✅

Phase 2: Refactoring (Modules 4-6)
├── Module 4: Multi-File Refactoring ← YOU ARE HERE
│   → Rename, extract, move, interface changes with Claude Code
├── Module 5: Framework Migration
│   → Flask→FastAPI, strangler fig pattern, migration testing
└── Module 6: Context Management for Large Projects
    → 1M tokens, chunking, CLAUDE.md, progressive context

Phase 3: Legacy and Project (Modules 7-8)
├── Module 7: Modernize Legacy Code
└── Module 8: Capstone Project — Full Migration

What you already know

From Phase 1 you arrive with:

  • A systematic onboarding method (Module 1)
  • Mastery of Explore for read-only investigation (Module 2)
  • An Architecture Map with dependency maps, flow analysis, and pattern/anti-pattern identification (Module 3)

From guide #7 (Testing) you arrive with:

  • Spec-first methodology
  • TDD with Claude Code
  • Regression tests and coverage

Where are we headed?

This module teaches you the fundamental types of refactoring. Module 5 scales to the framework level (Flask→FastAPI). Module 6 gives you the tools to do all of this on large projects that don't fit in the context window. And Module 8 integrates everything into a full migration.


Professional Objective

By the end of this module, you'll be able to plan and execute coordinated refactoring that touches multiple files using Claude Code as your main tool — with regression tests that guarantee the behavior didn't change.

By the end of this module you'll be able to:

  • ✅ Execute a cross-file rename refactoring: rename a function/class and update all the references
  • ✅ Apply extract function/class: pull logic into a new module and update the callers
  • ✅ Execute move module: move files and update all the imports
  • ✅ Propagate interface changes: modify a function signature and update the implementations/consumers
  • ✅ Write regression tests BEFORE refactoring
  • ✅ Use Claude Code as a coordinator of multi-file changes
  • ✅ Verify that the refactoring preserved the behavior

A Real Refactoring: IDE vs Coordinated Claude Code

To anchor the module, consider a typical medium-sized task:

Task: Extract the price calculation logic (which currently lives in 3 Flask route handlers) into a new pricing_service.py. The logic is partially duplicated, has 4 private helper functions, and the handlers use it with slightly different arguments.

Approach A: IDE only (PyCharm, VS Code)

1. Locate the duplicated code by reading the 3 handlers
   manually. (~15 min)

2. Create pricing_service.py and copy the code.
   Decide how to unify the 3 slightly
   different versions. (~30 min)

3. Update handler 1: import the service, replace
   the logic. Adjust arguments. Test. (~20 min)

4. Repeat for handler 2 and handler 3. Each with its
   subtleties. (~40 min)

5. Find the existing tests (if any) and adjust them.
   Probably break some. (~30 min)

6. Debug the breakage. Look for indirect references
   you forgot. (~45 min)

TOTAL: ~3 hours. Bug risk: HIGH (manual).

Approach B: Coordinated Claude Code (this module)

1. RESEARCH (M2 techniques, you already master them)
   "Find all the functions that calculate a price,
    regardless of what they're called. List file, function,
    differences between them."
   → Claude Code lists the 3 locations and differences. (~3 min)

2. REGRESSION TESTS (Capsule 05)
   "Write regression tests that capture the current behavior
    of the 3 versions, including edge cases."
   → Tests pass against the current code. Safety net active. (~10 min)

3. PLAN
   "We're going to extract pricing_service.py with a unified function
    that accepts the arguments of the 3 variants via optional
    parameters. Then update the 3 handlers."

4. EXTRACT (Capsule 02)
   "Create pricing_service.py with the unified function. Keep
    the handlers using their old logic for now."
   → Service created. Tests still green. (~5 min)

5. INTERFACE CHANGES (Capsule 04)
   "Update handler 1 to use pricing_service. Keep
    handlers 2 and 3 untouched."
   → Handler 1's tests green. The other 2 green. (~3 min)

6. Repeat step 5 for handlers 2 and 3, one at a time.
   → Tests green at each step. (~6 min)

7. Cleanup: remove the old duplicated functions
   now that nobody uses them. (~3 min)

TOTAL: ~30 minutes. Bug risk: LOW (tests green at each step).

6× faster. Radically lower regression risk.

The difference isn't "Claude Code is smarter than an IDE." The difference is:

  • Claude Code reads all the relevant files before changing anything (Capsules 02-03)
  • Regression tests act as a continuous safety net (Capsule 05)
  • Verified incremental changes avoid the "everything broke at the end" (Capsule 04)
  • You direct, you don't accept the first attempt (the principle from Module 5 of guide #1)

This module trains you to execute this flow by default — so that a multi-file refactoring stops being a day of work and becomes an hour.


Module Progression

Module Map

CapsuleTopicWhat you'll learn
02Rename and Extract Cross-FileFundamental refactorings: renaming and extracting with automatic reference updates
03Move Module and Updating ImportsReorganize the file structure without breaking imports
04Interface Changes and PropagationModify interfaces and propagate the changes to all consumers
05Regression Tests for RefactoringThe tests→refactor→verify cycle as the golden rule
06Project: Coordinated RefactoringRefactor a feature that touches 5+ files with tests

Learning flow

You start with the simplest refactorings (rename, extract), which are the most frequent. Then you move up to move module, which affects imports across the whole codebase. Then interface changes, which is the most complex because it propagates changes to multiple implementations. Capsule 05 gives you the testing framework that applies to all the previous ones. And the final project integrates everything into a real 5+ file refactoring.

The complexity progression is:

Rename (1 name, N files)
  → Extract (1 block → new module, N callers)
    → Move (1 file → new location, N imports)
      → Interface (1 signature → N implementations + N callers)

Connection with the Project

This module's project: Coordinated Refactoring

You're going to receive (or choose) a codebase with a feature that needs refactoring: business logic mixed with routing, duplicated functions, inconsistent naming, or god objects. You execute a coordinated refactoring with Claude Code: you write tests first, make the changes, and verify that the tests pass.

Connection with the guide's project

In Module 8 (Capstone Project), multi-file refactoring is one of the steps of the full migration. The Module 3 Architecture Map identifies what to refactor. This module gives you the techniques to execute that refactoring.


Limits: What This Module WON'T Do

  • ❌ Framework migration — That's Module 5. Here you refactor within the same framework.
  • ❌ Complete rewrite — Refactoring preserves behavior. Rewrite starts from scratch. Here we do refactoring.
  • ❌ Architecture design — We don't design the ideal architecture. We improve the existing one with incremental changes.
  • ❌ Performance optimization — Refactoring improves structure, not performance. Optimization is a different goal.
  • ❌ Testing from scratch — We assume you know TDD from guide #7. Here we apply regression tests to refactoring.

The Core Principle

Tests first, refactoring later.

This principle is non-negotiable. Before each refactoring:

  1. Write tests that capture the current behavior
  2. Verify that the tests pass
  3. Execute the refactoring
  4. Verify that the tests still pass
  5. If they pass: the refactoring was successful
  6. If they fail: something broke — investigate before continuing

Without tests, how do you know the refactoring didn't break anything? You don't. And "it seems to work" isn't a professional verification.


Traps to Avoid While Taking This Module

Five predictable misunderstandings. Anticipate them before you start.

1. "Tests are optional if the refactoring is simple"

No. The definition of "simple" is retrospective: it seemed simple until something broke. Regression tests are cheap (Claude Code generates them in minutes) and they eliminate the entire category of "I broke something and didn't notice until the customer reported it." The module's rule is absolute: tests first, no exceptions.

2. "Cleaning everything at once is more efficient"

The opposite. Each refactoring must be incremental and verifiable: rename now, extract later, move afterward. If you make 4 changes together and the tests fail, you don't know which one broke what. If you make them one at a time with tests between each step, you know exactly where the problem is. Capsule 05 develops the cycle.

3. "Refactoring includes improving the architecture"

Not in this module. Refactoring preserves behavior while changing structure within the current paradigm. If you want to redesign the architecture (e.g. monolith → microservices), that's Module 5 (migration) or a different project. Mixing refactoring with redesign increases the risk and the opacity of the change.

4. "Claude Code is going to refactor autonomously"

No. You direct, Claude Code coordinates. The difference: you decide what to extract, what to move, what to rename — Claude Code applies the changes in the right files while keeping consistency. If you delegate the decision to it ("clean this up"), it's going to make decisions you didn't want. Guide #1 Module 5 gave you the framework — here you apply it.

5. "If the tests pass, the refactoring is perfect"

Green tests are necessary but not sufficient. Also verify: (1) the change diff is reasonable and doesn't include surprises, (2) the new structure is really clearer, (3) you didn't introduce new duplication while removing the old. Capsule 05 gives you the complete post-refactoring checklist.


Diagnosis: What's Your Starting Point?

Five questions to calibrate before you start.

Question 1: The last time you renamed a function used in 10+ files, how did you do it?

If you said "F2 in my IDE": it works for simple cases (same language, same project, no meta-programming). Capsule 02 shows you the cases where the IDE fails and Claude Code resolves them.

If you said "grep + sed": fast but dangerous (it can touch strings and comments). Capsule 02 teaches you the right approach.

Question 2: Do you write tests before refactoring, after, or never?

If you said "before": you're on the right track. Capsule 05 gives you a formal structure for regression tests.

If you said "after" or "never": capsule 05 is a priority. It's the highest-leverage habit change in the module.

Question 3: When you move a file, what happens to the imports in the rest of the codebase?

If you said "I update them by hand / my IDE updates them": it depends on the IDE and the language. Capsule 03 shows you how Claude Code does it reliably regardless of the setup.

If you said "I haven't had to do it": you're going to do it in the module project (5+ files involved).

Question 4: Have you changed the signature of a function that had 8+ callers? How did you ensure all the callers were updated correctly?

If you have a process: capsule 04 formalizes it as a reusable pattern.

If you don't: capsule 04 teaches it to you. Interface changes are the highest-risk refactorings and this module gives you a safe way to execute them.

Question 5: Can you tell a refactoring apart from an architectural improvement?

If yes: you're going to use this module correctly (refactoring) and reserve architectural improvements for Module 5 or dedicated projects.

If not: the "Limits" section above is your starting point. The distinction is critical — mixing them doubles the risk of any change.

If you hesitated on 3 or more: this module fills critical gaps for the rest of Phase 2. If you answered them all with clear criteria, use it as a focused review of capsule 04 (interface changes), which is usually where experienced developers make the most mistakes.


Evidence of Success

Before moving on to Module 5 (Framework Migration), you should be able to:

  • ✅ Execute a rename that updates 10+ references across different files without breaking anything
  • ✅ Extract logic into a new module and have all the callers keep working
  • ✅ Move a file and have all the imports update correctly
  • ✅ Change a function's signature and propagate the change to all the consumers
  • ✅ Write regression tests before each refactoring out of habit (not out of effort)
  • ✅ Give Claude Code a refactoring instruction and trust that it coordinates the changes correctly
  • ✅ Identify when a change crosses the line from "refactoring" and becomes "redesign" (Module 5)

If any one isn't met at the end, go back to the corresponding capsule. Module 5 (framework migration) uses these techniques at a larger scale — without mastering them here, the migration becomes fragile.


Summary

  • This module opens Phase 2: Refactoring — from understanding to modifying
  • The focus is coordinated multi-file refactoring using Claude Code
  • The 4 types of refactoring: rename, extract, move, interface changes
  • Regression tests are a mandatory prerequisite of every refactoring
  • The tests → refactor → verify cycle is the golden rule
  • Claude Code is the coordinator that reads the whole codebase and makes coherent changes
  • The project applies everything in a real 5+ file refactoring
  • The difference between "3 hours with high risk" and "30 minutes with low risk" from the initial scenario is exactly what this module teaches

Next capsule: 02 — Rename and Extract Cross-File — the two most frequent refactorings. We start here because they're the base of the others: if you understand how Claude Code coordinates rename and extract, the rest are extensions.


Additional Resources

  1. Refactoring: Improving the Design of Existing Code - Martin Fowler - The bible of refactoring, second edition with JavaScript
  2. Working Effectively with Legacy Code - Michael Feathers - How to introduce tests into untested code so you can refactor
  3. Refactoring Guru - Catalog - A visual catalog of refactorings with before/after
  4. Claude Code Documentation - Official Claude Code reference
  5. Python Refactoring Patterns - Patterns specific to Python
  6. Kent Beck - Test-Driven Development - TDD as the foundation of safe refactoring

Module 4, Capsule 01 — Refactoring & Legacy Code with Claude Code Guide