Refactoring With AI
Improve the design of existing code in small, behavior-preserving steps, using tests as the safety net and AI for analysis and mechanical change.
Introduction
AI-assisted development produces code quickly, and quick code accumulates problems quickly: duplicated logic generated in separate sessions, inconsistent patterns, abstractions nobody asked for, and functions that grow with every prompt.
Refactoring means changing the internal structure of code without changing its observable behavior. It is how a code base stays easy to change. It is also an area where AI is genuinely helpful, provided you have the safety net that makes “without changing behavior” a checkable claim.
Learning Objectives
- Define refactoring and distinguish it from rewriting and from feature work.
- Establish preconditions for safe refactoring.
- Recognize common code smells and AI-specific structural problems.
- Apply small-step refactorings and verify behavior preservation.
- Use AI to analyze code, propose refactorings, and perform mechanical changes with review.
- Plan larger refactorings incrementally.
1. What Refactoring Is, and Is Not
| Activity | Changes behavior? | Example |
|---|---|---|
| Refactoring | No | Extract a function; rename a variable; move a class |
| Feature work | Yes | Reject a new class of invalid rows |
| Bug fix | Yes (corrects it) | Fix off-by-one in row numbering |
| Rewrite | Usually, and unpredictably | Replace the importer from scratch |
| Performance tuning | Not functionally, but risks it | Batch inserts |
Keep them separate: do not mix refactoring with behavior changes in the same commit. When something breaks, you want to know which kind of change broke it.
2. Preconditions
Do not refactor without:
- Tests that detect behavior changes in the code you will touch. If there are none, write characterization tests first: tests that record what the code does now, correct or not (lesson 9).
- A clean, committed starting state, so you can discard a failed attempt.
- A fast check you can run after every step.
- A reason. Refactor to make a specific upcoming change easier, or to remove a specific pain, not to satisfy taste.
Static types, linters, and the dependency-rule checker also catch many mistakes automatically, which makes mechanical refactoring safer.
3. Smells to Look For
| Smell | Typical signal | Common refactoring |
|---|---|---|
| Long function | Does several things; scrolling needed | Extract function |
| Duplicated logic | Same rule in two modules | Extract shared function or module |
| Poor naming | data, process, handle2 |
Rename |
| Large class or module | Many unrelated responsibilities | Split by responsibility |
| Primitive obsession | Strings and dicts everywhere | Introduce a small type |
| Deep nesting | Many levels of if |
Guard clauses; extract |
| Feature envy | Code uses another module’s data more than its own | Move function |
| Leaky boundary | Imports another module’s internals | Route through public interface |
Common in AI-assisted code:
- Near-duplicates created in different sessions that diverge over time.
- Over-abstraction: interfaces, factories, and layers with one implementation and no reason.
- Inconsistent patterns: three ways to handle errors, two date formats.
- Dead code left behind after iterations.
- Comments that restate the code or describe what the prompt asked.
- Defensive code for cases that cannot occur, which hides real errors.
4. Small Steps
The core technique is a loop of tiny changes, each verified:
1
2
3
4
1. Run the tests (all green).
2. Make one small structural change.
3. Run the tests.
4. If green, commit. If red, undo and try a smaller step.
Example (illustrative). Before:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def import_feedback(workspace_id, csv_text):
rows = list(csv.DictReader(io.StringIO(csv_text)))
imported, rejected, errors = 0, 0, []
for i, row in enumerate(rows, start=2):
if not row.get("body") or not row["body"].strip():
rejected += 1
errors.append(Error("MISSING_BODY", i))
continue
try:
d = datetime.strptime(row["date"], "%Y-%m-%d").date()
except (KeyError, ValueError):
rejected += 1
errors.append(Error("INVALID_DATE", i))
continue
# ... fingerprint, insert, counters ...
return Result(imported, rejected, errors)
After extracting validation into a pure function and leaving orchestration in the service:
1
2
3
4
5
6
7
8
9
10
def import_feedback(workspace_id, csv_text):
result = ImportResult()
for row_number, row in parse_rows(csv_text):
validation = validate_row(row)
if not validation.ok:
result.reject(row_number, validation.code)
continue
repo.insert_if_new(workspace_id, to_feedback(validation.value))
result.imported += 1
return result
Each extraction (parsing, validation, conversion) can be done and tested as its own step. The behavior, and the tests, do not change.
5. Using AI for Refactoring
AI is useful for:
- Analysis: identifying smells, duplication, and candidate extractions.
- Proposals: suggesting a sequence of small steps.
- Mechanical changes: renames, moves, signature changes across many files.
- Explaining unfamiliar code before you change it.
It is risky when asked to “clean up this module” in one go. The result may restructure everything, subtly change behavior, delete code that seemed unused, and produce a diff nobody can review.
1
2
3
4
5
6
7
8
9
10
11
12
Context: [function or module code, existing tests, ASSISTANT_INSTRUCTIONS.md]
Task: Propose a refactoring plan as a sequence of small steps, each of
which keeps all existing tests passing. For each step give: what moves
or changes, the smell it addresses, and how we will verify no behavior
changed.
Constraints:
- Do not change behavior or public signatures.
- Do not modify tests in the same step.
- No new dependencies.
- List anything you suspect is a bug rather than "fixing" it.
Then execute one step at a time, with a commit after each. If the assistant discovers a bug, note it, finish the refactoring, and fix the bug in a separate commit with its own test.
6. Verifying Behavior Preservation
Passing existing tests proves little if they were weak. Add independent evidence:
- Characterization or golden-master tests: run the old and new code on a broad set of inputs (including real or realistic samples) and compare outputs.
- Type checks and linters across the whole project.
- Mutation or coverage reports to see whether the tests actually exercise the code you changed (covered in the quality engineering course).
- A review of the diff focused on what changed in semantics, not only formatting.
Be alert to tests being edited to pass. If a refactoring requires a test change, ask why: it may be a legitimate change to an implementation detail, or a changed behavior.
7. Larger Refactorings
Big structural changes cannot be done in one session. Plan them incrementally:
- Mikado method: try the change, note what breaks, revert, solve the prerequisites first, and repeat, building a graph of prerequisite changes.
- Branch by abstraction: introduce an interface in front of the old implementation, build the new one behind it, switch over gradually, and remove the old one.
- Strangler approach: route a growing portion of traffic or calls to the new implementation while the old one continues to work.
- Time-box and schedule it: put refactoring in the backlog with a reason and an end condition. A refactoring with no end is a rewrite.
Pair a larger refactoring with a visible goal (“module X no longer imports module Y’s internals”) so you can tell when to stop.
8. Practical Exercise
For SignalDesk (or your project):
- Choose one function or module from slice 1 or 2 that has grown messy. Record the reason you are refactoring it.
- Verify it has adequate tests. If not, write characterization tests first.
- Ask the assistant for a stepwise plan using the prompt above. Edit it, and decide which steps to do.
- Execute the steps one at a time with a commit after each, running
make checkevery time. - Add one independent check (for example, golden-master comparison on a larger sample).
- Create a refactoring log: what changed, which smell it addressed, how behavior preservation was verified, and anything unexpected the assistant did.
Verification
You are ready to continue when:
- Each refactoring step is a separate commit with all checks passing.
- No behavior change is mixed into refactoring commits.
- Tests were not weakened or edited to pass without explanation.
- There is independent evidence that behavior was preserved.
- Suspected bugs were logged, not silently fixed.
Key Takeaways
- Refactoring changes structure, not behavior, and needs tests as its safety net.
- Work in tiny verified steps; undo rather than debug large failed attempts.
- AI is strong at analysis and mechanical changes, and dangerous at “clean it all up” requests.
- AI-generated code has its own smells: near-duplicates, over-abstraction, and inconsistency.
- Plan large refactorings incrementally, with a defined end.
What’s Next?
Even with good prompts, tests, and refactoring, code needs another pair of eyes. Next, we look at code review: how to review AI-generated and human-written changes effectively.