Sub topic 2
Refactoring versus migration: what changes and what must not
This chapter assumes you can read and write code in at least one language, use Git branches and commits, run a test suite and a linter from the command line, and have used an AI coding assistant before. It covers the distinction that shapes every later decision: whether a change is a refactoring or a migration, and what that means for how you direct a coding agent.
Two kinds of change
A refactoring changes the internal structure of code without changing its observable behavior. Callers, users, and tests see the same inputs and outputs before and after. Extracting a function, renaming a variable, splitting a large module, and removing duplication are all refactorings.
A migration moves code from one technology, version, or design to another. Examples include upgrading a library across a major version, moving from one web framework to another, changing a database driver, or replacing a callback API with async calls. A migration usually touches many files, depends on documentation for the new target, and may change behavior on purpose or by side effect.
The two overlap in practice. A migration often includes refactorings, and a refactoring sometimes prepares the ground for a migration. Still, the questions you ask differ, and so does the risk.
| Aspect | Refactoring | Migration |
|---|---|---|
| Goal | Improve structure, readability, or testability | Move to a new library, version, framework, or platform |
| Observable behavior | Must stay identical | Should stay identical for users, but internals and sometimes edge cases change |
| Typical size | One function to a few modules | Often dozens or hundreds of files |
| Source of truth | The existing code and its tests | The existing code plus the documentation of the new target |
| Main risk | Silent behavior drift | Behavior drift, plus misuse of an API the agent does not know well |
| Best safety net | Characterization tests | Characterization tests, staged rollout, and often both versions running side by side |
| Reversibility | Revert the commit | Revert per step, or switch back with a flag during rollout |
What changes and what must not
Before you write any prompt, write down two lists for the task.
- What changes: the structure, the names, the library calls, the file layout.
- What must not change: public function signatures, return values, error types, output formats, database schema, log messages that other systems parse, performance limits.
The second list is the contract. The agent cannot infer it reliably. If it is not stated, the agent will treat anything that is not tested as open to change. A short invoice example shows the pattern. This is a refactoring, so the contract is that format_invoice returns the same dictionary for the same input.
# Before
def format_invoice(items):
subtotal = sum(i["price"] * i["qty"] for i in items)
tax = round(subtotal * 0.2, 2)
return {"subtotal": subtotal, "tax": tax, "total": subtotal + tax}
# After: same inputs and outputs, tax logic extracted
TAX_RATE = 0.2
def calculate_tax(subtotal):
return round(subtotal * TAX_RATE, 2)
def format_invoice(items):
subtotal = sum(i["price"] * i["qty"] for i in items)
tax = calculate_tax(subtotal)
return {"subtotal": subtotal, "tax": tax, "total": subtotal + tax}The structure changed: there is a new function and a named constant. The behavior did not. Any test that called format_invoice before still passes after. If you saw round(subtotal * TAX_RATE, 1) in a diff, that would be behavior drift, and it would no longer be a refactoring.
Where the line blurs
Real tasks rarely arrive labeled. Use these checks to classify them.
- Does an external dependency or version change? If yes, it is a migration, even if the code edits look small.
- Is the intended behavior identical afterward? If yes and no dependency changes, it is a refactoring.
- Does the change fix a bug or add a feature? Then it is neither. Do it as a separate commit, or better a separate branch. Mixing a bug fix into a refactoring makes the diff impossible to judge, because a behavior change looks the same as a mistake.
- Is the new target documented in your project? If the agent must rely on its own memory of a library's API, the migration is riskier.
A common trap is the "refactoring that is really a migration." Replacing a hand-written date parser with a library is described as cleanup, but libraries disagree on edge cases such as two-digit years, time zones, and invalid input. Treat it as a migration: pin the behavior first, then swap.
How the agent's role differs
A coding agent works in a loop of reading files, editing them, running commands, and observing the results. That loop suits both kinds of change, but the weak points differ.
For a refactoring, the agent works from code that exists in the repository. Its main failure is drifting from the original behavior while "tidying up." It may drop an edge case, change a rounding rule, or reorder operations that had side effects. The defense is a test suite that fails when behavior changes. Where tests are thin, you add characterization tests first (a later chapter covers these in detail).
For a migration, the agent also depends on knowledge of the target. Its training data may describe an older version of the library, or mix two versions. It may call a function that does not exist in your version. The defenses are to point the agent at the real documentation or at the installed package source, to ask it to cite which API it is using, and to let a type checker or the test suite expose invented calls.
The agent's behavior is not the only variable. The scale matters too. A refactoring fits in one session and one review. A migration usually does not. It needs a plan, a way to track which files are done, and small steps that can be reviewed one by one.
Choosing an approach for each
Approach for a refactoring
- State the contract: what must not change.
- Confirm that tests cover the code. If not, add tests that record current behavior.
- Ask the agent for a short plan, then approve it.
- Apply one structural change at a time. Run tests after each one.
- Review the diff for anything unrelated to the stated goal.
A scoped task description makes the contract explicit. The text below states the goal, the files in scope, the behavior that must not change, a way to verify, and a request to plan before editing.
Refactor pricing.py: extract the tax calculation from format_invoice into its own function named calculate_tax.
Constraints:
- Do not change the public signature or the return value of format_invoice.
- Touch only pricing.py and tests/test_pricing.py.
- Run `pytest tests/test_pricing.py` before and after the change and report both results.
First describe your plan in a few bullet points. Wait for my approval before editing.Approach for a migration
- Define the source and the target, with exact versions.
- Collect the target's migration guide or changelog and give it to the agent.
- Pin current behavior with tests that exercise the code you will replace.
- Split the work into steps that each leave the code working, for example one module or one call pattern at a time.
- Use deterministic tools such as codemods for repetitive, mechanical edits, and keep the agent for cases that need judgment.
- Roll out gradually, and remove the old code only after the new path has proven itself.
Each step in a migration is itself small and verifiable. The workflow looks like this.
Pinning behavior before you start
Both approaches rest on a test that records what the code does now. A characterization test asserts current output, even when you are not sure the output is ideal. Its job is to detect change, not to prove correctness.
# tests/test_pricing.py
from pricing import format_price
def test_format_price_current_behavior():
# Expected values were recorded by running the existing code,
# not derived from a specification.
assert format_price(1234.5) == "$1,234.50"
assert format_price(0) == "$0.00"If the test fails after a change, the behavior changed. You then decide whether that was intended. In a refactoring it never is. In a migration it sometimes is, and you should record the decision in the commit message or the plan.
Checkpoints for both
Whatever the type, commit after each verified step. A bad step can then be discarded without losing earlier work.
git switch -c refactor/extract-calculate-tax
pytest
# let the agent make one small step, then check it
pytest && git add -A && git commit -m "Extract calculate_tax from format_invoice"
# if a later step goes wrong, discard it and keep the checkpoint
git restore .Note that git restore . discards uncommitted changes to tracked files and cannot be undone. That is the point of committing before each step. It also does not remove new untracked files the agent created, so check git status as well.
Common mistakes
- Mixing goals in one change. A refactoring plus a bug fix plus a dependency bump gives a diff nobody can review. Split them.
- Calling a migration a refactoring. The label affects how much care you take. If a dependency changes, use the migration approach.
- Leaving the contract unstated. "Clean this up" lets the agent decide what is allowed to change. Name what must stay fixed.
- Trusting the agent's memory of a library. For a migration, supply the version-specific documentation and rely on tests and type checks to catch invented APIs.
- Starting without a safety net. If no test would fail when behavior drifts, write one before the first edit.
- Doing everything at once. Large steps cannot be reverted cleanly. Prefer many small commits.
Summary of the working model
A refactoring keeps behavior fixed and changes structure, so the central tool is a test that fails on any behavior change. A migration changes the technology underneath, so you also need accurate information about the target, smaller steps, and a staged rollout. In both, you decide what must not change, state it to the agent, and check it after every step.
Exercise
You ask an agent to replace a hand-written CSV parser in your project with the standard library's csv module, "as a cleanup refactoring." The existing tests pass after the change, but a customer later reports that fields containing quoted line breaks now parse differently. Classify the task, explain what went wrong, and name two steps you would take before the change next time.
Show answer
This is a migration, not a refactoring, because the code now depends on a different implementation (the csv module) whose edge-case behavior can differ from the hand-written parser. The existing tests did not cover quoted line breaks, so the behavior change went unnoticed. Next time, first write characterization tests that record the current parser's output for edge cases such as quoted line breaks, embedded delimiters, and empty fields. Then do the swap in a small step on its own commit, review the diff, and decide for each differing result whether the new behavior is acceptable. Optionally also compare old and new parsers on sample production files before rollout.
Exercise
Write the "what changes" and "what must not change" lists for this task: upgrade a project from requests to httpx for all outgoing HTTP calls, keeping the application's behavior the same.
Show answer
What changes: the import statements, the client calls (for example requests.get becomes httpx.get or a shared httpx.Client), the dependency listing, and how exceptions are caught (requests.RequestException becomes httpx.HTTPError). What must not change: the public functions that wrap HTTP calls and their return values, timeout and retry behavior seen by callers, the headers and payloads sent to external services, how errors surface to callers, and the log messages other systems rely on. Note that httpx does not follow redirects by default while requests does, so redirect handling is an explicit item to pin with a test.