Skip to content

Lesson 10 of 28Working in real codebases

Changing Legacy Code Safely

Find out why odd code exists, size the blast radius, ship changes as a chain of small PRs, verify in production and delete dead code with evidence.

15 min read0/5 questions

Your ticket says "late fees should be 4%, not 5%". The function is in billing.py, last touched in 2021 by someone who left the company. It has no tests, it is called from a nightly job and two API routes, and it contains if invoice.customer_id == 4471: return 0 with the comment # see ticket. Nobody on the team wants to touch it, which is why the ticket landed on you. This is normal. Most of your career will be spent changing code that already works and already earns money, and doing that without breaking anything is a skill teams notice fast.

Legacy code pays the salaries

Michael Feathers, in Working Effectively with Legacy Code, defines legacy code as code without tests. A wider working definition is code people are afraid to change. Age is not the point. A six-month-old service with no tests and a vanished author is legacy. A ten-year-old module with a good suite is not.

Legacy code exists because the product succeeded. It shipped under a deadline, customers started using it, and every edge case a customer hit became another if. The people who knew why moved on. The code that survives long enough to become legacy is, almost by definition, the code the business depends on.

That shapes how you behave on a team:

  • Do not sneer. "Who wrote this garbage?" in a channel lands badly, because the author is often still in the company, sometimes in the meeting. The code was written with information and pressures you cannot see.
  • Treat it as a working system. Its behaviour, including the weird parts, is what customers rely on today. Your job is to change one thing, not to make it beautiful.
  • Make it a little safer each time. Every visit should leave behind more tests and more understanding than you found.

The mechanics of getting untested code under test (characterisation tests, golden masters, seams, sprout and wrap) are covered in Code Smells and Refactoring. This lesson is about the rest of the job: investigating, scoping, sequencing your pull requests, proving the change in production and cleaning up after.

Chesterton's fence: find out why first

G. K. Chesterton described a fence across a road. A reformer says "I see no use for this, let's clear it away." The wiser reply: "If you don't see the use of it, I certainly won't let you clear it away. Go and find out why it is there, and then you may come back and tell me you can destroy it."

In code, the fence is the sleep(2) before a retry, the hardcoded customer id, the try that swallows one specific error. It looks pointless. Often it is load-bearing: a vendor rate limit, a contract clause, a workaround for a bug in a library version you no longer use. Sometimes it really is pointless. Your job is to know which before you delete it.

Work up this ladder, cheapest first:

  1. Ask the history. git log -S finds the commit that added a string, and its message may explain everything. Git Archaeology: Bisect, Blame and Reflog goes deep on these tools.
  2. Follow the ticket. Commit messages and PR descriptions usually reference a ticket id. The ticket often has the original customer complaint.
  3. Find the people. git shortlog shows who has worked on a file. The CODEOWNERS file shows who owns it now. The author may have moved teams, not companies.
  4. Look at production. Logs and metrics tell you whether a branch ever runs, and for whom.

Here is that ladder on the fence from the ticket, in a real terminal session:

terminal
$ git log -S 4471 --oneline
61fa48e Waive late fees for Northwind (BILL-812)
 
$ git show -s --format='%an%n%n%B' 61fa48e
Tom Okafor
 
Waive late fees for Northwind (BILL-812)
 
Northwind's contract (signed 2021-11) exempts them from late fees.
Finance asked for a code fix until the contracts table exists.
 
$ git shortlog -sn HEAD -- billing.py
     1	Priya Shah
     1	Tom Okafor

Two minutes of searching turned "delete this weird line" into "this is a contract obligation, and finance owns the decision". Notice that the code comment (# see ticket) was useless while the commit message was excellent. That is a lesson for your own commits too.

When the trail goes cold, ask a human, and ask well: "I'm changing late fees in billing.py. There's a special case for customer 4471 added in BILL-812. Is that contract still active, and should the new 4% rate apply to them?" That is a question someone can answer in one message. When you get the answer, write it down where the next person will find it: a comment with the reason, or better, a test named test_northwind_is_exempt_from_late_fees.

Quick check
You find time.sleep(2) before every call to a payment vendor in a legacy module. Nothing explains it. What do you do first?
Need a nudge? A hint rules out a wrong answer.

Size the blast radius before you start

Before writing code, find out what can break. The blast radius is everything affected if your change is wrong. It decides how much safety net you need. Changing a label on an internal admin page needs little. Changing how money is calculated needs a lot.

Answer these before you estimate the ticket:

  • Who calls it? Use your editor's "find references", then search for the function name as a string, because Python's getattr, JavaScript bracket access, config files and templates hide calls from the editor.
  • Who calls it from outside this repo? Other services, cron jobs, data pipelines, a reporting query someone in finance runs every month-end. A search across your organisation's code host finds most of these.
  • What does it write? Code that only reads is easy to roll back. Code that writes to the database, sends email or charges cards leaves effects that a revert does not undo.
  • How often does it run? A path that runs a million times a day shows a bug within minutes. A path that runs at year-end shows it in eleven months.
  • How often does it change? A file with heavy churn is a hotspot (Technical Debt shows how to find them). Changes there conflict with other people's work, so coordinate.
Blast radius of changing late_fee()
late_fee(): the changelate_fee()the changeInvoice API: 2 routesInvoice API2 routesNightly job: dunning runNightly jobdunning runinvoices table: fee writteninvoices tablefee writtenEmail vendor: overdue noticesEmail vendoroverdue noticesFinance report: month-end SQLFinance reportmonth-end SQLcallscallswritessendsread by

Start from the function. The editor finds two direct callers.

1/5

Write the answers in the ticket or the PR description. It shows your reviewer you understand the risk, and it often changes the estimate. "One-line change" becomes "one line, plus a backfill question for finance, plus a flag because the nightly job emails customers".

Ship it as a chain of small pull requests

The safest way to change legacy code is never one big PR. It is a sequence where each step is easy to review and easy to revert, and only one step changes behaviour.

Changing the late fee in four PRs
  1. PR 1

    Pin current behaviour

    Characterisation tests for `late_fee()`, including the Northwind exemption and the rounding. No production code changes, so review is quick and the risk is close to zero.

  2. PR 2

    Refactor with no behaviour change

    Extract the rate into a constant and the exemption into `is_fee_exempt()`, using the IDE's automated refactorings. The PR 1 tests pass unchanged, which is the proof.

  3. PR 3

    Change behaviour behind a flag

    Read the rate from a flag: 5% when off, 4% when on. Update the pinned test deliberately, with the reason in the PR. Turn it on for internal accounts first.

  4. PR 4

    Remove the flag

    After a full billing cycle at 4% with no surprises, delete the flag and the old path. Without this step you have added a permanent branch.

This looks slower. It is usually faster, because each PR gets reviewed in minutes instead of sitting for days while a reviewer gathers courage for a 900-line diff. And if PR 3 goes wrong, you flip a flag instead of reverting a mixed change and losing the tests with it.

A reviewer can check a pure refactor quickly, because the question is only "did behaviour change?" and the unchanged tests answer it. The same lines mixed with a rule change need line-by-line suspicion. Say which kind each PR is in its title or description.

The boy-scout rule, without scope creep

"Leave the code better than you found it" is good advice that goes wrong in legacy code. You rename one variable, then fix the function next to it, then notice the module has three date libraries, and your 10-line ticket is a 600-line PR touching code with no tests.

A rule of thumb that keeps it honest:

  • Clean up what you touch, in files your ticket already changes, in a separate commit.
  • If the cleanup is bigger than the change itself, it becomes its own PR before or after the change.
  • Anything beyond that becomes a ticket with what you found, so the knowledge is not lost and the team can prioritise it.
Put it in order5 steps

Order the pull requests for safely changing a calculation in an untested legacy module.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Prove it in production with a shadow run

Tests check the inputs you thought of. Production has the ones you did not. For risky rewrites of pure calculations, teams run the old and new code side by side on real traffic, return the old result to the user, and record every disagreement. GitHub popularised this with its open source Scientist library, and the idea is simple enough to write yourself.

Here, a shipping-cost function is being rewritten as a table. Run it and see what the experiment catches.

Python
import random # Old code: in production for years. Its answer is the one users get.def old_shipping(weight_kg, country): if country == "UK": if weight_kg <= 2: return 399 return 399 + int((weight_kg - 2) * 150) return 1299 # New code: a table-driven rewrite we are not yet sure about.RATES = {"UK": (399, 2, 150)}def new_shipping(weight_kg, country): base, free_kg, per_kg = RATES.get(country, (1299, 0, 0)) extra = max(0, weight_kg - free_kg) return base + round(extra * per_kg) MISMATCHES = [] def experiment(name, control, candidate, *args, sample=1.0): result = control(*args) # users always get the old answer if random.random() < sample: # only try the new code on a sample try: new = candidate(*args) except Exception as exc: # a crash in new code must not hurt users new = f"raised {type(exc).__name__}" if new != result: MISMATCHES.append((name, args, result, new)) return result random.seed(7)orders = [(1.5, "UK"), (2.0, "UK"), (3.3, "UK"), (7.1, "UK"), (4.0, "FR"), (2.7, "UK")]for weight, country in orders: experiment("shipping", old_shipping, new_shipping, weight, country) print(f"{len(orders)} orders, {len(MISMATCHES)} mismatches")for name, args, old, new in MISMATCHES: print(f" {name}{args}: old={old} new={new}")
Output
Press Run (⌘ Enter) to see what happens.

One order in six differs by a penny. The old code truncates with int() and the new one rounds. Is the old behaviour a bug? Maybe. But it is the behaviour customers and finance reconcile against, so changing it is a product decision, not a side effect of a refactor. The experiment turned an invisible difference into a question you can take to the right person.

Predict the outputPython

What does this print?

print(int((3.3 - 2) * 150), round((3.3 - 2) * 150))
Need a nudge? Hints walk you through it.

Shadow runs have rules. Only run the candidate for code without side effects: never send the email or write the row twice. Sample a percentage of traffic, because you are paying for the work twice. Compare normalised results (sorted lists, rounded floats) or you drown in noise. And give the experiment an end date, like any flag.

Strangler fig at team scale

When a whole module or service has to be replaced, the answer is still incremental. Code Smells and Refactoring covers the strangler fig and branch by abstraction at the code level. On a team, three extra things decide whether it works.

A routing point you control. Somewhere a single decision says "this request goes to new code, that one to old". A flag per slice (per route, per customer segment, per report) lets you move traffic and roll back without a deploy.

A plan for the last 10%. Strangler projects usually stall on the weird remaining cases: the one enterprise customer, the admin report nobody understands. The old system then runs forever next to the new one, and you maintain both. Put the decommission date in the plan from day one, and treat "old system deleted" as the definition of done.

Visible progress. A dashboard showing the share of traffic on the new path keeps the project funded. Leadership can see value arrive every sprint instead of being asked to trust a rewrite for a year.

The alternative, the big-bang rewrite, fails often enough to have a name. Fred Brooks called it the second-system effect: the replacement collects every feature people wished the first one had, so it grows larger and later than planned, while the old system keeps changing underneath it. The rewrite has to match years of undocumented fixes before it can ship anything at all.

Delete dead code, with evidence

Dead code costs you every time someone reads it, searches past it or updates it during an upgrade. Deleting it is one of the best changes you can make, as long as it really is dead.

Static tools find candidates. vulture reports unused functions, classes and variables in Python, with a confidence score. knip reports unused files, exports and dependencies in JavaScript and TypeScript projects. Both produce false positives for code that is reached dynamically: plugin registries, framework conventions, functions named in config or called by a cron entry in another repo.

Runtime evidence confirms them. Add a log line or a metric counter to the suspect path, ship it, and wait. How long depends on the business cycle: a week proves nothing about a month-end job, and a quarter proves nothing about the annual tax export. Coverage collected in production (some teams sample it on a few servers) gives the same evidence for a whole codebase at once.

Then delete it in a small PR whose description links the evidence: "zero calls in 45 days, including a month-end". Git keeps the old code if you ever need it, so there is no reason to comment it out "just in case".

Match the pairs0/5 matched

Match each situation to the technique that fits it best.

Choose an item, then its match on the other side.

Upgrading dependencies and frameworks

Legacy code is often legacy because its dependencies are years behind. Each skipped version makes the next upgrade bigger, until "upgrade the framework" is a quarter-long project nobody will fund. The cheapest strategy is to never fall far behind.

  • Automate small upgrades. Dependabot or Renovate opens PRs for new versions. Group minor and patch bumps so they arrive as one weekly PR, and let CI decide. A suite you trust makes this nearly free.
  • One major version at a time. Going from version 3 to 6 in one jump means three sets of breaking changes at once, and when something breaks you cannot tell which one. Upgrade 3 to 4, ship, then 4 to 5.
  • Read the migration guide before the code. Major releases list their breaking changes. Ten minutes with the guide saves an afternoon of guessing at a stack trace.
  • Turn deprecation warnings into errors in tests. In pytest, filterwarnings = ["error::DeprecationWarning"] under [tool.pytest.ini_options] makes the suite fail on deprecated calls, so you fix them while the old API still works. Expect to add ignores for warnings from third-party packages.
  • Use codemods for the mechanical part. Many frameworks ship official codemods for their own upgrades (Next.js has @next/codemod), and the Python community has tools like pyupgrade and django-upgrade. Run them, review a sample of the diff, and let the tests check the rest. Check each tool's docs for the exact command for your versions.
  • Upgrade in its own PR. Never mix a framework bump with a feature. When something breaks in production, you want the revert to remove exactly one thing.
Quick check
A static tool flags export_annual_tax_report() as unused. You add a counter and see zero calls after three weeks. What should you do?
Need a nudge? A hint rules out a wrong answer.
Key terms
legacy code
Code without tests, or more broadly code people are afraid to change. Usually old, valuable and missing its original authors.
Chesterton's fence
The rule that you should find out why something exists before you remove it.
blast radius
Everything that is affected if a change is wrong: callers, stored data, emails sent, downstream reports.
shadow run
Running new code alongside old code on real traffic, returning the old result and recording any disagreement.
second-system effect
Fred Brooks' observation that a replacement system tends to be over-designed, bigger and later than planned.
dead code
Code that never runs in production. Find candidates with static tools, then confirm with runtime evidence before deleting.
codemod
A program that rewrites source code through its syntax tree, used for large mechanical changes such as framework upgrades.