LESSON 9

Understanding Legacy and Unfamiliar Code With AI

Build an accurate mental model of code you did not write: map it, read its history, pin its behavior with characterization tests, and use AI to explore while verifying every claim.

Introduction

Most professional software work happens in code someone else wrote: a dependency you must debug, a component inherited from another team, or a system whose authors left years ago. Michael Feathers’ well-known working definition of legacy code is simply code without tests, and that is a useful one: you cannot change it confidently because you cannot tell what you broke.

AI assistants can read thousands of lines quickly and summarize them. That is valuable. It is also dangerous, because a confident but wrong explanation of code you do not know is hard to detect. This lesson shows how to use AI to explore while keeping every claim anchored to evidence.

Learning Objectives

  • Explore an unfamiliar code base systematically.
  • Use version history and tests as sources of understanding.
  • Use AI to summarize, trace, and generate questions, and verify its claims by running code.
  • Write characterization tests to pin down existing behavior.
  • Find seams for safe change and plan incremental modernization.
  • Document what you learn for the next person.

1. The Scenario

Illustrative scenario: a pilot customer shares a script they use to export feedback from their helpdesk tool. SignalDesk’s team wants to reuse parts of it for an import adapter. The script is 1,800 lines, has no tests, minimal comments, and its author has left the customer’s company.

(If you do not have such a case, use any unfamiliar open-source library or an old repository you have access to. The approach is the same.)

The goal is not to understand every line. It is to understand enough to change it safely for a specific purpose.

2. Start With Questions, Not Code

Write down what you need to know before reading anything:

  • What does this code do, from the outside (inputs, outputs, side effects)?
  • How is it run, configured, and deployed?
  • What does it depend on (services, files, environment, libraries)?
  • Where is the logic I need to reuse or change?
  • What breaks if I change it?

A specific purpose focuses the search. “Understand everything” has no end.

3. Map the Territory

Build a map from the outside in:

  1. Entry points: main functions, command-line arguments, scheduled jobs, endpoints.
  2. Structure: directories, modules, and their apparent responsibilities.
  3. Dependencies: libraries, external services, files, environment variables. Check versions and whether they are still maintained.
  4. Data: input formats, schemas, output formats, and persistent state.
  5. Runtime behavior: run it with safe sample data and observe logs, output, and side effects.

Tools that help: a dependency graph generator, grep and symbol search, the debugger, and logging added temporarily on a branch. Run the code in an isolated environment (a container or a disposable branch) with non-sensitive sample data, especially if it touches external systems.

4. Read the History

Version control contains intent that the code does not:

1
2
3
4
git log --oneline --follow -- path/to/file    # history of one file
git log -S "retry_count"                      # when did this text appear or disappear?
git blame -w -C path/to/file                  # who last changed each line, ignoring whitespace and moves
git log --stat --since="2 years ago"          # which files change most
  • Frequently changed files show where the real complexity or instability is.
  • Commit messages and linked tickets often explain strange code (“workaround for customer X’s export bug”).
  • Files that never change may be stable and safe, or dead.

If the history is gone, look for documentation, issue trackers, and people. A conversation with a former maintainer often outweighs hours of reading.

5. Use AI as an Exploration Partner

AI can accelerate every step above, but its explanations are hypotheses.

1
2
3
4
5
6
7
8
9
10
11
12
Context: [the file or module, plus how it is invoked, if known]

Task: Help me understand this code. Provide:
1. A summary of what it appears to do, in plain language.
2. The main flow, step by step, citing function names and line numbers.
3. Inputs, outputs, and side effects (files, network, database).
4. Assumptions the code makes (formats, ordering, environment).
5. Parts that are unclear, surprising, or look like bugs.
6. Ten questions I should ask the author or verify by running it.

Cite the code for every claim. If you are inferring rather than
reading, say so explicitly. Do not guess about code you cannot see.

Good uses: summarizing a module, tracing a call path, listing external dependencies, explaining an unfamiliar idiom, generating a glossary of domain terms found in the code, and suggesting where to look next.

Verification practices:

  • Ask for citations (file, function, line) and check them.
  • Run the code with a specific input and compare the actual behavior to the explanation.
  • Ask the assistant to explain the same code a second way or critique its own explanation; disagreement between answers signals uncertainty.
  • Be wary of explanations based on names and comments: legacy code often does something different from what its names say.
  • Remember context limits: for large code bases, the assistant sees only what it was given or retrieved. A summary of one file says nothing about callers elsewhere.

6. Characterization Tests

A characterization test records what the code actually does today, whether or not that is correct. It turns unknown behavior into a safety net.

Procedure:

  1. Choose a unit or entry point you plan to change.
  2. Feed it representative inputs, including odd ones.
  3. Record the actual outputs and side effects as expected values.
  4. When behavior surprises you, record it, mark it as “surprising,” and decide later whether it is a bug.
1
2
3
4
def test_legacy_export_parses_dates_day_first():
    # Characterization: current behavior, not necessarily intended.
    rows = legacy_parse("12/03/2026,Search is slow\n")
    assert rows[0].date == date(2026, 3, 12)   # day/month order

AI can help generate input cases and draft the tests, and can suggest which edge cases to probe. But the expected values must come from actually running the code, never from the assistant’s prediction of what it would do.

For code with side effects or complex output, golden-master (snapshot) tests compare full output against saved real output for a set of realistic inputs.

7. Finding Seams

A seam is a place where you can change behavior without editing the code around it: an interface, a function parameter, a configuration value, a module boundary. Seams let you insert tests or replacements.

Typical moves for getting legacy code under test:

  • Extract a pure function from a tangled one, and test that.
  • Introduce a parameter for a hard-coded dependency (clock, file path, HTTP client).
  • Wrap the legacy component behind your own interface, so the rest of the system depends on the interface, not the legacy details.

Wrapping legacy code behind an interface also sets up modernization: you can later replace the implementation behind the interface step by step (the strangler approach from lesson 7). For SignalDesk, the helpdesk adapter implements the same FeedbackSource interface as CSV import, hiding the legacy parsing logic behind it.

8. Decide: Reuse, Wrap, Rewrite, or Avoid

Option When it fits
Reuse as is Behavior is understood, tested, and acceptable
Wrap The behavior is useful but the code is messy or risky; limit your exposure
Rewrite part A well-understood piece is blocking progress and can be pinned by tests
Avoid The cost of understanding exceeds the value, or risk is too high

A full rewrite is rarely the right first move: it discards embedded knowledge about real-world edge cases. If the code has worked for years, assume it encodes lessons you have not yet learned.

9. Record What You Learn

Understanding that lives only in your head is lost. Produce a short code map document in the repository:

  • Purpose and entry points.
  • Main flow and key modules.
  • Dependencies and environment needs.
  • Known surprises and suspected bugs.
  • How to run it and its tests.
  • Open questions.
  • Which parts are verified (by test or experiment) and which are only inferred.

Keep the distinction between verified and inferred explicit; AI-generated summaries are especially prone to blur it.

10. Practical Exercise

For SignalDesk (or any unfamiliar code you have access to):

  1. Write your specific purpose and the questions you need answered.
  2. Build the map: entry points, structure, dependencies, data, and a sample run.
  3. Read the history for the parts you need and note at least three insights from commit messages or blame.
  4. Use the AI exploration prompt on two parts of the code. Verify at least five claims by running or reading the code, and record any that were wrong.
  5. Write characterization tests for the function or entry point you plan to use, with expected values taken from real runs.
  6. Choose reuse, wrap, rewrite, or avoid, and write the reasons.
  7. Produce the code map document.

Verification

You are ready to continue when:

  • You have a written purpose and a map of the relevant code.
  • AI claims were checked against the code or by execution.
  • Characterization tests exist, with expected values taken from actual behavior.
  • The decision about reuse, wrap, rewrite, or avoid is documented.
  • The code map marks verified versus inferred knowledge.

Key Takeaways

  • Start with a specific purpose and questions, not a quest to read everything.
  • Version history, tests, and running the code are better evidence than explanations.
  • AI explanations are hypotheses; require citations and verify by execution.
  • Characterization tests turn unknown behavior into a safety net.
  • Wrap and replace incrementally instead of rewriting wholesale.

What’s Next?

You now have the practices to write, review, change, and understand code with AI. The final question is how much autonomy to give the tools, and where humans must stay in control. Next, we look at human-in-the-loop development.