Every team eventually inherits code it did not write: code that works, that customers depend on, and that nobody fully understands anymore. Then a new feature lands, and the only way forward is through that code. If you want to refactor legacy code safely, the goal is simple: change the structure without changing what the software does.
Refactoring is not rewriting. A rewrite throws the old code away and starts over. A refactor keeps the behavior and improves the shape, one small step at a time. spreading the risk across steps you can check and undo.
The sequence below works on real codebases: map the code, pin its behavior with tests, change it in small steps, and ship each one. It also covers the no-tests-no-time case, and the mistakes that turn a tidy refactor into a broken release.
Why legacy code is hard to change
Legacy code is not bad code by definition. Often it is code that survived, and it earned its quirks by handling edge cases nobody wrote down: a tax rule for one region, a retry loop added after one outage, a field that looks unused but feeds a report nobody owns.
That is why “just clean it up” fails. A developer sees a branch that looks dead, deletes it, and breaks a report that runs once a quarter. Learn what the code does first, and build a way to notice when you changed it by accident.
Refactoring competes with feature work, and managers ask why working code needs touching. Unmaintainable code slows every future change, and the cost shows up as technical debt that grows quietly until a simple feature takes weeks. A refactor earns its keep when it makes the next change cheaper.
How to refactor legacy code safely: four rules
Four rules cover most of the risk. First, never change behavior and structure in the same commit: if one commit both fixes a bug and renames half the functions, nobody can tell which part broke production. Second, keep each step small enough to review in one sitting and revert in one command. Third, run the tests after every step. Fourth, ship the small steps instead of collecting them into one large release.
These rules sound slow. In practice they are faster, because they remove the long debugging session at the end. Three days of small verified steps beats one day of work and a week of fixing regressions.
Step 1: Map the code before you touch it
Before editing anything, spend time reading. Find the entry points: the routes, queue handlers, and scheduled jobs that call the code you need to change. Trace the data from input to output, and note the side effects: database writes, emails, file writes, calls to other services. Side effects are where refactors break things.
Write down what you find, so the next person skips the detective work: the callers, the inputs, and the outputs each caller depends on. If one caller ignores a return value another relies on, know that before you change the return type.
Look for seams: places where the code already has a boundary you can work with. A function that takes plain data and returns plain data is a good seam. A 400-line function that reads from the database, formats a PDF, and sends an email has none yet, and your first job is to create one.
Step 2: Put a safety net in place first
Tests are what make legacy code refactoring possible. Without them, every change is a guess. You do not need full coverage, only tests that pin down the behavior of the code you are changing.
Start with characterization tests: tests that describe what the code does today, even if what it does looks wrong. Feed the function real inputs, record the outputs, and assert those outputs. The point is not to judge the behavior. It is to freeze it, so you can tell the moment a refactor changes it. Tests that catch real bugs focus on behavior and edge cases, not on a coverage number.
Where the code is too tangled with the database or network for unit tests, test at a higher level instead. A test that calls an API endpoint and checks the response covers more ground than a dozen unit tests you cannot write yet. Integration tests are the right tool when the code has too many dependencies to isolate.
Confirm the tests pass before you change anything. A failing test before you start tells you nothing. A passing suite is your baseline: if it still passes after your change, the behavior held.
Step 3: Make small changes and ship them
With the safety net in place, start with the smallest change that helps. Extract a function. Rename a variable so its purpose is clear. Replace a magic number with a named constant. Keep each change small enough to explain in one sentence.
After each change, run the tests. If they pass, commit. If they fail, the last change broke them. That is the point of small steps.
Resist the urge to fix everything you see. A refactor that touches ten files to fix one smell usually introduces two new problems. Note the rest as follow-up work and keep the current change focused.
Ship the change. A refactor that sits in a branch for a month goes stale and grows until nobody wants to review it. Small merged changes compound; a large unmerged branch rots.
Step 4: Replace big pieces with the strangler fig pattern
Some parts are too large to refactor in place. A whole module or an old service may need replacing rather than tidying. The safe way is the strangler fig pattern: build the new piece alongside the old one, route a small share of traffic to it, and grow that share until the old piece handles nothing. Then delete it.
The old code keeps serving production while the new code proves itself. If the new code fails, route traffic back. There is no flag day, no weekend cutover, and no single moment where everything can break at once. The same idea works at system scale, which is why it shows up in migrations from a monolith to microservices that avoid a big rewrite.
Two details decide whether this works: a clean boundary so traffic can move either way, and a way to compare outputs by running the same inputs through both. Find the differences before the old code is gone.
What to do when there are no tests and no time
Sometimes there are no tests, nobody will approve a week of writing them, and the change still has to happen. Shrink the safety net to fit the time you have.
Write one test for the exact behavior you are about to change, even if it is a rough script rather than a proper test. A small script that calls the function with a known input and prints the output beats no check at all. Save the output, then run the same script after the change and compare.
Use the production data you already have. Logs, database snapshots, and existing reports show what the code actually does. Capture a sample of real outputs before the change, then run the same inputs after and diff the results. This is refactoring without breaking changes done on a budget: you are still pinning behavior, just with a script instead of a suite.
Keep the change even smaller than usual. If you cannot test it well, do not change much. Rename one thing. Extract one function. Ship it, watch it, then do the next piece.
Mistakes that break working code
- Changing behavior and structure together. A refactor that also fixes a bug or adds a feature is no longer a refactor. Split the work so each change has one reason.
- Deleting code that looks dead. Code can be dead in the main path and alive in a quarterly job or a script nobody told you about. Search for callers, check scheduled jobs, and wait before deleting.
- Refactoring without running the code. Reading is not enough. Run the tests, run the app, hit the endpoint. Static analysis catches syntax. Only execution catches behavior.
- Trusting a rewrite to be safer. A rewrite discards years of bug fixes along with the mess. Old code is ugly partly because it handles cases the new code has not met yet.
- Letting the refactor grow. “While I am here” is how a two-hour tidy becomes a two-week project. Write down the extra work and do it separately.
Legacy code rewards patience. Map it, pin its behavior with tests, change it in steps you can check, and ship each step. The code does not need to become beautiful. It needs to become safe to change, and a little easier to change each time you touch it. That is how you refactor legacy code safely, one verified step at a time.