Skip to content

Lesson 9 of 28Working in real codebases

Reading Code You Didn't Write

Find your way around an unfamiliar codebase: read with a goal, get it running, trace one request end to end, and use search, debuggers, tests and Git history.

20 min read0/4 questions

Reviewing a diff means reading a small piece of someone else's code. Most days you need to find your way around a whole codebase you have never seen. It is your fourth day. Your first ticket says: "Refund emails show the wrong currency for EU customers." The repo has 300,000 lines, four services and nobody who wrote the refund code still works here. Nobody expects you to understand all of it, and you never will. What you need is a way to find the twenty lines that matter in under a day. Most of an engineer's working time goes on reading code, not writing it, and the people who read well are the ones who look fast at everything else.

Read with a question, not a plan to understand everything

Opening src/ and reading files from the top is the most common mistake. You run out of attention long before you reach anything relevant, and nothing sticks because you had no reason to remember it.

Start with one question you want answered. For the ticket: "Where does the refund email get its currency from?" Write it at the top of a notes file. Every file you open, ask whether it helps answer that question. If not, close it. You will learn the rest of the codebase gradually, one ticket at a time, and that is fine.

There are two directions to read in, and you switch between them:

  • Top-down: start at an entry point (a route, a CLI command) and follow calls inward. Good for "how does this feature work?"
  • Bottom-up: start at a specific detail (an error message, a column name, the word on the screen) and search outward for who uses it. Good for "where does this bug come from?"

A bug ticket usually starts bottom-up. A new feature usually starts top-down.

Get it running first

Code you can run is ten times easier to understand than code you can only read, because you can poke it and watch what happens. Before reading any business logic, get the app running and the tests passing on your machine. The files that do this are also the best map of the project:

Read these first: the repo's map
  • shop-api/
  • README.mdhow to run it, often slightly out of date
  • Makefilethe commands people really use: make dev, make test
  • pyproject.tomldependencies and tool config
  • docker-compose.ymlwhat it needs: postgres, redis, a mail catcher
  • .env.exampleevery setting the app reads
  • .github/
  • workflows/
  • ci.ymlwhat "passing" means here
  • app/
  • main.pyentry point: builds the app, mounts routers
  • routes/
  • refunds.pyHTTP layer
  • services/
  • refunds.pybusiness logic
  • workers/
  • email_worker.pyqueue consumer that sends mail
  • emails/
  • refund.htmlthe template the customer sees
  • tests/
  • test_refunds.pyexecutable documentation

The README says how people think you run it. The Makefile (or package.json scripts, or a justfile) says how they actually run it. The CI config is the most honest of all: it is the exact set of steps that must pass for code to merge, and it cannot drift out of date without breaking the build. docker-compose.yml lists the moving parts. .env.example tells you every knob.

If the setup instructions are wrong, and they often are, fix them as you go. Updating the README is a classic first PR, and it saves the next new hire the same hour.

Find the entry points and trace one path

Every program has a few places where control enters from outside: main, HTTP routes, CLI commands, queue consumers, scheduled jobs, event handlers. In a FastAPI app, main.py creates the app and mounts routers, so it lists every route file. In a Next.js app, the app/ folder structure is the route list.

Once you have an entry point, trace one real request end to end. For the refund bug:

One refund, end to end
Admin UIRouteServiceDatabaseQueueEmail workerCustomerPOST /orders/5521/refundrefund_order(order_id, amount)load order, insert refundorder row (currency: NULL)publish RefundIssuedRefundIssued eventRefund of £37.98

Start where the action starts. rg for the URL path finds the route in seconds.

1/7

Notice what tracing gives you that reading files does not: the order things happen in, the shape of the data at each hop, and the moment the code goes asynchronous. Async boundaries (queues, events, background tasks, webhooks) are where "go to definition" stops working. Search for the event or job name instead.

Predict the outputPython

What does this print?

order = {"id": 5521, "currency": None}
a = order.get("currency", "GBP")
b = order.get("currency") or "GBP"
print(a, b)
Need a nudge? Hints walk you through it.

Your tools

Search is your best friend. Fast text search across the whole repo answers most "where is" questions. The best search target is something the user can see: the exact text of an error message, a button label, an email subject line. It appears in very few places, and one of them is next to the code you want.

rg -n "Your refund of"              # the exact words in the emailrg -n "RefundIssued"                # who publishes and who consumes the eventrg -n "currency" app/workers        # narrow to one folderrg -l "def refund_order"            # just the file names

rg (ripgrep) is fast and skips files in .gitignore. Your editor's global search (Ctrl/Cmd+Shift+F) does the same job.

Let the editor do the navigation. Text search finds strings. The language server understands code:

  • Go to definition (F12 in VS Code): jump from a call to the function.
  • Find all references (Shift+F12): every caller. Before changing a function, look at all of them.
  • Call hierarchy: the tree of who calls this, and who calls them.
  • Hover: the type of a variable without opening another file.

Watch it run. Set a breakpoint at the point you care about, trigger the action, and look at the real values. The Debugging Python lesson covers breakpoint() and the editor debugger. When a debugger is awkward (a worker in Docker, a staging environment), log the shape of the data instead of dumping all of it. A small helper does this:

Python
def shape(value, depth=0, max_items=1): """Describe the structure of a value without dumping all of it.""" pad = " " * depth if isinstance(value, dict): print(f"{pad}dict with {len(value)} keys") for key, item in value.items(): print(f"{pad} {key!r}:", end=" ") if isinstance(item, (dict, list)): print() shape(item, depth + 2, max_items) else: print(type(item).__name__, repr(item)[:30]) elif isinstance(value, list): print(f"{pad}list of {len(value)}") for item in value[:max_items]: shape(item, depth + 1, max_items) else: print(f"{pad}{type(value).__name__} {repr(value)[:30]}") # What the email worker actually receives (from a staging log line).payload = { "refund_id": "rf_8812", "order": {"id": 5521, "currency": None, "customer": {"id": 77, "country": "DE"}}, "lines": [{"sku": "MUG-01", "amount": 1299}, {"sku": "TEE-04", "amount": 2499}], "amount": 3798,}shape(payload)
Output
Press Run (⌘ Enter) to see what happens.

In one glance: the currency is None, but the customer's country is there. That suggests a fix (derive the currency for old orders, or backfill the column) and a question for the team (why are some orders missing a currency?).

Match the pairs0/5 matched

Match each question to the fastest tool for answering it.

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

Reading one file well

When you do need to read a whole file, do not start at line 1 and grind. Skim it in passes:

  1. Imports. They tell you what this file touches: the database, an HTTP client, the payments SDK, a queue. A file that imports nothing from outside is pure logic and safe to reason about alone.
  2. The public names. Function and class signatures, exported names, anything without a leading underscore. That is the file's contract with the rest of the code.
  3. The bodies you need. Only now open the functions on your path. Collapse the rest in your editor.

Signatures and types carry a lot of meaning cheaply. def refund_order(order_id: int, amount_pence: int) -> Refund already tells you units, inputs and output before you read a single line inside it.

Tests are documentation that cannot lie

Comments drift. Tests that still pass describe what the code really does today. Before reading a complicated module, read its test file: test names are often a list of the rules (test_refund_rejects_more_than_paid, test_partial_refund_keeps_order_open). Missing tests are information too. If there is no test for currencies, nobody pinned that behaviour, which is a strong hint about where the bug lives.

A failing test is also the best way to confirm your understanding: write a test for the case you think is broken, watch it fail for the reason you expected, then fix the code. That test becomes part of your PR.

History tells you why

The code tells you what. Git tells you why, if you ask the right way. The Git archaeology lesson covers these tools in depth; for reading, a few commands go a long way:

git log --oneline --follow -- app/workers/email_worker.py   # history, even across renamesgit log -L "/def build_refund_email/,+20:app/workers/email_worker.py"   # how this function evolvedgit log -S "or 'GBP'" --oneline     # the commit that added or removed this textgit blame -w -C app/workers/email_worker.py   # last change per line, ignoring whitespace, following moved linesgit shortlog -sn HEAD -- app/workers   # who has worked here most: people to ask

A commit message like "Default currency to GBP for legacy imports (FIN-212)" is gold: it names the ticket, and the ticket or the PR usually explains the decision. Before you remove anything that looks pointless, find out why it was added. The Changing legacy code safely lesson covers that habit in detail.

Sketch and take notes

Keep a plain text notes file while you read. It is the cheapest tool there is, and it stops you reading the same file three times.

notes/refund-currency.md
Question: where does the refund email get its currency?
 
Path: POST /orders/{id}/refund -> routes/refunds.py -> services/refunds.py:refund_order
      -> publishes RefundIssued -> workers/email_worker.py:build_refund_email
 
Terms: "legacy import" = orders migrated from the old shop in 2023, may lack currency
Owners: payments team (Ana) owns services/refunds.py; Lee wrote the worker
Open questions: why are some currencies NULL? Is there a backfill ticket?

A box-and-arrow sketch on paper does the same for structure. You will throw most notes away, but the terms and owners sections become your personal glossary for the whole job.

Using an AI assistant to read code

Asking an AI assistant "explain this module" is a fast way to get a first map, and it is genuinely useful. It is also often confidently wrong about details: it may describe what code like this usually does rather than what this code does, or miss a branch. Use it like a colleague who skimmed the code once:

  • Ask for file paths and line numbers with every claim, then open them.
  • Ask it questions you can check ("which functions read order.currency?") rather than for summaries you cannot.
  • Treat its explanation as a hypothesis, and confirm the important parts with a breakpoint or a test.

The Context Engineering lesson covers how to give it the right files so its answers are grounded.

Quick check
An AI assistant tells you the email worker 'always uses the order's currency field'. What do you do?
Need a nudge? A hint rules out a wrong answer.

Know when to ask

Struggling alone for a whole day looks diligent but is usually waste. Asking after two minutes means you learn nothing and interrupt someone for a question you could have answered. A timebox fixes both: give yourself something like 30 to 60 minutes of honest effort on one question, then ask. Ask well:

I'm on FIN-388 (refund emails show GBP for EU customers).
Traced it to email_worker.py:41, which falls back to GBP when order.currency is None.
Some older orders have NULL currency (order 5521 in staging, country DE).
Question: is NULL currency expected for legacy imports, or is there a backfill
I should know about? I was going to derive it from the customer's country.

It says what you are working on, what you found, what you tried and what you plan to do. Someone can answer that in one line, and it shows that you did the work. That is what seniors mean when they say a new hire "asks good questions".

Put it in order6 steps

You get a bug ticket in an unfamiliar repo. Put these steps in a sensible order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
entry point
A place where control enters a program from outside: main, an HTTP route, a CLI command, a queue consumer or a scheduled job.
top-down reading
Starting at an entry point and following calls inward to see how a feature works.
bottom-up reading
Starting from a specific detail, such as an error message, and searching outward for the code that uses it.
find all references
An editor feature, powered by the language server, that lists every place a function or variable is used.
async boundary
A hop through a queue, event or background job, where go-to-definition stops and you must search for the event name.
pickaxe search
git log -S 'text': finds the commits that added or removed a given string.
timebox
A fixed amount of time you allow yourself on a problem before asking for help.