Notes Tutorials

Reading other people's code

Most of the code you'll work with was written by someone else, often someone who isn't around to ask. How to get oriented, follow one path instead of reading everything, find things fast, ask git why a line exists, and pin down behavior before you change it.

7 min readAlso available in Bahasa Indonesia →

Learning to program usually means writing code from an empty file. Working as a programmer mostly means something else: opening a project that already has thousands of lines, written by people you may never meet, and changing one small thing without breaking the rest. Part 11 quoted PEP 8: “code is read much more often than it is written.” This part is about the reading.

There’s even a research field for it. Program comprehension is “a domain of computer science concerned with the ways software engineers maintain existing source code.” You don’t need the research, though. You need a few habits.

Don’t start at line 1

The most common mistake is opening the first file and reading top to bottom, like a book. Code isn’t written to be read that way. You’ll drown in details before you know which ones matter.

Instead, read from the outside in:

  1. What is it for? Read the README, the project description, the folder names. One sentence is enough: “a shop backend that calculates order totals and imports orders from CSV.”
  2. How does it run? Find the entry point: main.py, index.php, main.go, package.json scripts, a Makefile. Run it if you can. A running program answers questions that reading can’t.
  3. How is it organized? Look at the folder tree, not the files. Which parts are about the web, which about data, which about business rules?
  4. Are there tests? Tests are examples of how the code is meant to be used, written by people who knew it.

Follow one path

Once you’re oriented, don’t try to understand everything. Pick one thing that happens and follow it all the way through: one page request, one button, one report, one command. You’ll touch maybe five or ten files out of hundreds, and you’ll understand those well.

It’s the same decomposition from part 9, in reverse. There you split a problem into functions. Here you start from a function and work out which problem it belongs to.

Write down what you find as you go. A short list is enough:

POST /orders
  → routes/orders.py: create_order()
  → shop/orders.py: order_total(items)
  → shop/pricing.py: final_price(price, qty)   ← discount logic lives here

That little map is worth more than an hour of reading, and it’s what you’ll want next week when you’ve forgotten.

Find things fast

A small example project is used for the rest of this part: a shop with orders.py and pricing.py, and three commits of history.

Search the whole project. git grep will “Look for specified patterns in the tracked files in the work tree”. It only searches files git knows about, so it skips node_modules and build output:

$ git grep -n "final_price"
shop/orders.py:1:from shop.pricing import final_price
shop/orders.py:4:    return sum(final_price(i["price"], i["qty"]) for i in items)
shop/pricing.py:1:def final_price(price, qty):

One command shows where it’s defined and every place it’s used.

Jump to the definition. Every serious editor has “Go to definition” and “Find all references”. Learn the shortcut. It’s the single most useful reading tool you have.

Ask the running program. When names are reused or code is loaded dynamically, the language itself can tell you where something comes from. Python’s inspect module helps “get information about live objects”, and inspect.getsourcefile returns “the name of the Python source file in which an object was defined”:

import inspect
from shop.orders import final_price
print(inspect.getsourcefile(final_price))
print(inspect.getsource(final_price))
…/shop/pricing.py
def final_price(price, qty):
    total = price * qty
    if qty >= 10:
        total = total * 95 // 100
    if total < 0:
        total = 0
    return total

final_price was imported through shop.orders, but it lives in shop/pricing.py. PHP’s Reflection does the same; getFileName “Gets the file name from a user-defined function”:

$f = new ReflectionFunction('finalPrice');
echo $f->getFileName(), ':', $f->getStartLine(), '-', $f->getEndLine();
// → …/src/pricing.php:2-8

Ask the history why

Code tells you what happens. It rarely tells you why. The history often does.

git blame will “Show what revision and author last modified each line of a file.” Say you’re puzzled by these two lines in final_price. How could a total be negative?

$ git blame -L 5,6 --date=short shop/pricing.py
19474ea4 (Ana 2026-08-21 5)     if total < 0:
19474ea4 (Ana 2026-08-21 6)         total = 0

And the commit message for 19474ea:

Fix negative totals from refund rows (qty = -1) in CSV import

Now it makes sense: the CSV import includes refund rows with negative quantities, and those once produced negative totals. Without the history you might have “cleaned up” that odd check and brought the bug back.

git log -S finds the commits that added or removed a piece of text. It’s useful when you want to know when a rule was introduced:

$ git log -S "95 // 100" --oneline
5492637 Add 5% bulk discount for 10+ items

This is also a good argument for writing commit messages that explain why. The next person reading git blame might be you.

Strange code usually has a reason

There’s a principle for this called Chesterton’s fence: “reforms should not be made until the reasoning behind the existing state of affairs is understood.” If you find a fence in the middle of a field and can’t see what it’s for, find out before you tear it down.

In code, the fence is the odd if, the extra sleep(1), the special case for one customer ID. Sometimes it really is a leftover. Often it’s a fix for something you haven’t run into yet. Check the history, search for related tickets, ask someone. Then decide.

Run it and watch

Reading is guessing. Running is checking. When you’re not sure what a piece of code does, make it tell you:

  • Call it directly with a few inputs in a REPL or a small script.
  • Print the values at the point you’re unsure about.
  • Use a debugger. In Python, breakpoint() “drops you into the debugger at the call site”; you can then inspect every variable and step line by line. PHP has Xdebug, Go has Delve, and browsers have DevTools for JavaScript.

Calling final_price with a few inputs takes seconds and answers several questions at once:

(100, 1) 100
(100, 10) 950
(333, 10) 3163
(100, -1) 0

Notice (333, 10): 3,330 minus 5% is 3,163.5, and the code returns 3,163. The // rounds down. Is that intended? You wouldn’t have asked if you’d only read the code.

Pin it down before you change it

Before changing code you don’t fully understand, write tests that record what it does now. These are called characterization tests: “a means to describe (characterize) the actual behavior of an existing piece of software”, which “protect existing behavior of legacy code against unintended changes”.

from shop.pricing import final_price

# Characterization tests: they record what the code does today,
# not what we think it should do.
def test_single_item():
    assert final_price(100, 1) == 100

def test_bulk_discount_starts_at_10():
    assert final_price(100, 9) == 900
    assert final_price(100, 10) == 950

def test_discount_rounds_down():
    assert final_price(333, 10) == 3163

def test_refund_rows_become_zero():
    assert final_price(100, -1) == 0
....                                                                     [100%]
4 passed in 0.01s

Note that the rounding test records the current behavior even though you’re not sure it’s right. That’s the point: now if your change alters the rounding, a test fails and you decide whether that’s intended, instead of finding out from a customer. Part 14 covers testing properly.

Habits that help

  • Read with a question. “Where is the discount calculated?” is answerable. “How does this project work?” isn’t, at least not at first.
  • Keep notes and a map. File names, function names, one line each.
  • Rename and comment locally while you explore, on a throwaway branch, if it helps you understand. Throw it away afterwards or turn it into a real cleanup.
  • Don’t judge too fast. Code that looks bad was often written under constraints you can’t see: a deadline, an old library, a bug in a browser that’s long gone.
  • Ask. If the author is around, five minutes of their time can save you an afternoon. Come with a specific question and what you’ve already found.

Why this matters day to day

  • Most work is changing existing code. Bug fixes, new features, and upgrades all start with reading.
  • Onboarding. A new job or a new project is mostly weeks of reading. Doing it systematically shortens that.
  • Fewer regressions. Understanding why a line exists, and pinning behavior with tests, is how you avoid reintroducing old bugs.
  • AI-generated code is someone else’s code. Everything here applies: run it, follow one path, check the odd parts, and pin down its behavior before you trust it. Part 24 comes back to this.

Try it yourself

  1. Pick an open-source project you use. Without reading any code, write one sentence about what it does and find its entry point.
  2. Choose one feature and follow it from entry point to the function that does the work. Write the map as in the example above.
  3. Run git blame on a confusing line in a project with history. Does the commit message explain it?
  4. Write three characterization tests for a function you didn’t write, including one for a behavior that surprised you.

Summary

  • Read outside in: purpose, entry point, structure, tests. Run it if you can.
  • Follow one path through the code instead of reading everything; write down the map.
  • Find things with search (git grep), go to definition, and the language’s own introspection (inspect, Reflection).
  • Ask the history why: git blame, git log -S, and good commit messages.
  • Respect Chesterton’s fence: understand odd code before removing it.
  • Run and observe, and pin current behavior with characterization tests before changing it.

References