Nguyen Le Phong

Working With Legacy Code Without Starting Over

Odd legacy code usually encodes old bug fixes.

You open a file called billing_calc_v2_final.js. The main function is 300 lines long. Halfway down there's a condition that checks whether the customer is in the EU and the invoice is dated before March 2019, and if both are true it skips a rounding step. No comment, no ticket number. git blame points to someone who left the company four years ago. Your first thought is the classic one: who wrote this?

Fair question, but it won't help for long. This post is about what does help: reading odd code as history, pinning down what it does before you touch it, making small changes that make the next change safer, and thinking hard before you reach for a rewrite.

An engineer reads an old codebase late in the evening, with architecture sketches and flow diagrams spread across the desk.
Legacy code looks scary right up until you understand it. Start by investigating, and save the verdict for later.

Odd code usually has a reason

That EU condition probably isn't random. Maybe a tax rule changed. Maybe one big customer had a contract that said so. Maybe it was a midnight hotfix for a bug that cost real money. Legacy code looks strange because it carries history you weren't there for: a rushed launch, a database limit, a team that shrank from three engineers to one, a deadline that mattered more than elegance.

Joel Spolsky made this point back in 2000 in Things You Should Never Do, Part I. That ugly function with the weird special cases? Each of those cases is often a bug fix, and in his words, "each of these bugs took weeks of real-world usage before they were found." He also gives the reason engineers misjudge old code so often: it's harder to read code than to write it. (There's a whole post on that here: Reading Code Is Harder Than Writing It.)

So before deleting a branch, ask what old data might still go through it. Before renaming a field, check which report, export or integration reads it. Before calling something bad design, find out what the team knew at the time. None of this means you have to keep the code forever. It means you understand it before you change it.

Pin down what it does today

The most useful tool here comes from Michael Feathers, author of Working Effectively with Legacy Code. He calls it a characterization test: a test that documents what the system actually does, not what you wish it did. The trick is almost lazy. Write a test with a placeholder expected value, run it, see what comes out, and paste that in as the expectation.

test('invoice total, EU customer, invoice dated before 2019', () => {
  const total = calculateInvoiceTotal(euInvoice2018)
  expect(total).toBe(0) // placeholder: run once, then paste what you see
})

// after the first run:
expect(total).toBe(1184.5) // what the code does today, odd or not

If 1184.5 looks wrong, write that down and ask around before you "fix" it, because someone may depend on it. Feathers puts it neatly: once a system goes into production, in a way it becomes its own specification. A characterization test turns that unwritten spec into something the next person can read and run. The engineer who knew the edge case may be gone, and the ticket may be buried in an old tracker, but the test stays in the repo.

Two engineers trace an old code path together, adding tests and marking one small change on a whiteboard.
One test, one clarified rule, one safer branch. Each one leaves the code a little less mysterious than yesterday.

Small changes that make the next one safer

With a few tests in place, the boring improvements become safe to make:

  • Extract one pure calculation out of the 300-line function and give it its own tests.
  • Rename a variable once you're sure what it holds. flag2 becomes skipRoundingForLegacyEuInvoices.
  • Add logging around the branch you're unsure about, then check after a week whether anything still goes through it.
  • Move a rule that's copied in three places to the one place it belongs.

None of these feels like a grand refactor. Together they give you footholds, and each one makes the next change a bit cheaper and a bit less scary.

Before you reach for a rewrite

The rewrite urge is strong, and Spolsky's essay is the classic warning. Netscape decided to rewrite its browser from scratch and went almost three years without a major release, handing competitors years to catch up. He called it "the single worst strategic mistake that any software company can make." A rewrite has to recreate both the behavior everyone knows about and the behavior nobody wrote down, and the second kind is where rewrites tend to fall apart.

Martin Fowler offers the alternative in Strangler Fig Application. He named it after the figs he saw in Queensland's rain forests, which grow around a host tree and slowly replace it. Build the new behavior next to the old system, move pieces over one at a time, and let the old code shrink. You need seams where you can split the system, plus some temporary code so old and new can run side by side. Fowler argues that the lower risk and earlier value are worth that temporary cost, and notes that in his experience all-at-once replacements have usually gone down in flames.

So before proposing a rewrite, ask a smaller question: can we make the next change safer without replacing everything? Sometimes the answer is an adapter around the legacy module. Sometimes new features go behind a cleaner boundary while the old path stays put. Sometimes a rewrite really is the right call, when the old system blocks changes the business needs and the team has a migration plan it believes in. The goal is to keep what the old code learned while you lower the risk.

A team reviews a migration plan where the legacy module stays in place while new boundaries are added one at a time.
Keep one foot on the part that works. Move only the boundary you understand and have tested.

Legacy code is hard on people too

An old codebase can make a capable engineer feel slow and a new teammate feel like they don't belong. Code review turns into archaeology. A healthy team names that cost out loud without blaming whoever came before. "This module is hard to follow" and "the people who wrote it did their best under the constraints they had" can both be true.

It also helps to remember that everything you ship today becomes someone else's legacy code. If you want the next engineer to read your decisions with some context, start by reading the last team's decisions that way.

Try this week

  • Pick the scariest function you'll touch this sprint and write one characterization test for it before changing anything.
  • When you find a strange condition, spend ten minutes in git log and the old tickets before deciding it's dead code.
  • Rename one variable whose meaning you've just worked out.
  • If someone proposes a rewrite, ask what the first slice of a strangler-fig migration would look like.
What did you think?

Frequently asked questions

What is a characterization test?
A test that records what legacy code does today, odd behavior included. Michael Feathers' method: write a test with a placeholder expected value, run it, then paste in the actual result. It lets you refactor and know right away if behavior changed.
Should I rewrite legacy code from scratch?
Usually not as a first move. A rewrite has to recreate behavior nobody documented, and Netscape's rewrite left it almost three years without a major release. Replacing the system slice by slice, the strangler fig approach, is lower risk.
What is the strangler fig pattern?
Martin Fowler's name for replacing a legacy system gradually. You build new behavior alongside the old system, move functionality over piece by piece through seams, and retire the old code once nothing uses it.
How do I start working on a legacy codebase?
Read before you write. Trace one path end to end, check git history and old tickets for strange conditions, add a characterization test around the code you need to change, then make one small, safe improvement.