Lesson 2 of 8

Code Comprehension · The method · Lesson 2 of 8

Read code you didn’t write

Before you hunt for a bug you need to know what the code is meant to do and what it actually does. A way to read unfamiliar code fast, without getting lost.

By Akshay, software engineer, India

On this page

Start with what it should do

Before the code, read the contract: the function’s name, its inputs, what it returns, and the report or test. Say it in one sentence: “paginate takes the full list, a page number starting at 1 and a page size, and returns that page’s items.” If you can’t say that sentence, ask. A bug is only a bug against what the code is supposed to do.

Skim top-down, then go deep

First pass: find the entry point and the main path, and skip the details. What gets called, in what order, and where does the result come from? Second pass: go deep only where the report points. In a codebase, the failing test tells you which function to start in.

Name what you see, out loud: “this loop builds a map from user id to orders”, “this branch handles the empty cart”. Naming turns lines into ideas you can reason about, and the interviewer hears you understand it.

Trace one small input by hand

Pick the smallest input that matters and walk it through, writing the variables down as they change. A trace table is the fastest debugger there is, and it works in a code review where you can’t run anything.

function sumTo(n) {
  let total = 0;
  for (let i = 1; i < n; i++) total += i;
  return total;
}
sumTo(3)   // should be 1 + 2 + 3 = 6

 i | total
 1 |   1
 2 |   3
 (i = 3: 3 < 3 is false, stop)  → returns 3, not 6

Three rows and the bug is plain: the loop stops one step early (< should be <=).

Where bugs hide

While you read, slow down at the places bugs like to live. The drill families in this course are exactly these:

  • Edges: < vs <=, -1, the first and last item, empty input.
  • Missing values: null, undefined, a missing key, zero.
  • Shared objects: assignments that don’t copy, defaults that are shared, in-place sorts.
  • Conversions: strings that look like numbers, integer division, floats for money.
  • Async: a missing await, a loop that doesn’t wait, two things racing.
  • State: caches, globals and anything that survives between calls.
Remember
  • Say the contract in one sentence before reading the code.
  • Skim the main path first; go deep only where the report points.
  • Trace the smallest interesting input by hand, writing variables down.
  • Slow down at edges, missing values, shared objects, conversions, async and state.
Your progress stays on this device.