Claude Code in Your Development Flow
Lesson 2: Refactoring Existing Code with Claude Code
Lesson Objectives
By the end of this lesson, students should be able to:
- Frame a refactoring request that produces safe, targeted changes
- Apply the plan-then-apply workflow for larger refactors
- Validate that a refactored implementation preserves the original behavior
- Identify when a refactor scope is too large for a single Claude Code task
Lesson Content
Framing refactoring requests.
Refactoring requests must specify: what to change, to what target state, and what must be preserved. Without all three, Claude makes judgment calls that may not match your intentions:
- Weak: "Refactor this function"
- Strong: "Refactor
parseUserConfig()to use early returns instead of nested conditions. The public interface and all return values must remain unchanged. Tests inconfig.test.jsmust continue to pass."
The third component – what must be preserved – is the most commonly omitted. It is also the most important for safe refactoring.
The plan-then-apply workflow.
For any non-trivial refactor:
- Ask Claude to describe the refactoring plan: what it will change and how
- Review the plan against your intent
- Ask Claude to identify any tests that cover the code being refactored
- Apply the refactoring
- Run the tests
- Review the diff
This workflow prevents surprises and ensures you understand the change before it is applied.
Validating behavior preservation.
A refactored implementation that changes public behavior is not a refactoring – it is a change. Validate behavior preservation:
- Existing tests pass (necessary but not sufficient – tests may not cover all behavior)
- The public interface (function signatures, return types, error behavior) is unchanged
- Edge cases behave identically (null inputs, empty collections, error conditions)
If the existing test coverage is weak, ask Claude to identify the edge cases that should be tested before refactoring – and add those tests first.
Recognizing scope creep in refactors.
Broad refactoring requests ("refactor this module") invite Claude to make many changes simultaneously – increasing the review surface and the risk of undetected behavior changes. Scope refactors to a single concern:
- Naming only (rename variables/functions)
- Structure only (early returns, extract functions)
- Pattern migration only (async/await from callbacks)
Single-concern refactors produce clean, reviewable diffs. Mixed-concern refactors produce complex diffs that are hard to review confidently.
Enroll to continue this lesson.
The preview above shows the lesson objectives and opening lesson content. Enroll to view the full lesson, complete the practice work, and take the lesson quiz.
