Reading Existing Code
Reading existing code is the skill of building an accurate mental model of a system you did not write. Developers spend most of their time reading code and less of it writing.
Start from the outside
Do not read a codebase top to bottom. Work from the outside in:
- Read the README and docs. Find out what the system is for, how to build it and how to run it.
- Look at the folder structure. Names of top-level folders usually reveal the layers or features. See Repository Structure and Layered Architecture.
- Find the entry points, where execution starts: a
mainfunction, a web route, a message handler, a scheduled job. - Pick one feature and follow it from entry point to database or external call and back.
Reading techniques
- Follow one request. Tracing a single concrete scenario is far easier than understanding everything at once.
- Run the application and use a debugger or log output to watch real values and the real call order.
- Read the tests. They show intended behaviour and example inputs, and are often better documentation than comments.
- Use your editor. Go to Definition, Find References and the call hierarchy let you jump instead of searching by hand. See Navigating Large Codebases.
- Consult history.
git blame <file>shows who last changed each line, and the commit message often explains why.git log -p -- <file>shows how a file evolved.
Take notes
Sketch what you learn: a list of the main modules, a small diagram of the request path, and a list of questions. Writing forces you to find the gaps in your understanding, and the notes are useful to the next newcomer. See Documentation Skills.
Things that mislead you
- Code that looks odd is not necessarily wrong. It may handle an edge case you have not met yet. Check history and tests before “cleaning it up”.
- Names can mislead. Confirm what a function really does by reading its body or running it.
- Do not refactor while learning. Understand first, then change. Make small, safe improvements later with refactoring once tests protect you.
- Ask after you have tried. Bring a specific question and what you already found. See Asking Good Questions.
Try it
Choose a feature in a codebase you do not know well. Find its entry point and follow one request through every layer, writing down each file and function you pass. Then use git blame on one confusing line and read the commit that introduced it. Compare your notes with a colleague who knows the code.
Common mistakes
- Reading the codebase top to bottom.
- Assuming odd-looking code is wrong and cleaning it up.
- Trusting names without checking what the function does.
- Refactoring while still learning the code.
Check yourself
- What are the first things to read in an unfamiliar codebase?
- How can git blame help you understand a confusing line?
- Why check history and tests before cleaning up odd code?