A bug report arrives. The first instinct of most developers is to open the file that seems related and start reading. The second instinct, when the first does not produce an answer quickly, is to add console.log statements until something surprising appears.
That works eventually. But it is not systematic. The better approach looks more like scientific method than code reading.
Reproduce before anything else
A bug you cannot reproduce reliably is not a bug you can fix reliably. Before touching any code, get a consistent reproduction case. What input, what state, what sequence of events causes the failure?
A minimal reproduction also tells you a lot. If the bug disappears when you remove half the data, the remaining half matters.
Form a hypothesis before looking at code
Once you can reproduce the bug, state a hypothesis before opening the debugger. "I think the cache is returning stale data after a write." Write it down.
This forces you to reason about the system rather than grep for symptoms. It also tells you exactly what to look for.
The binary search approach
For bugs with unclear origin, binary search narrows the problem space logarithmically. Comment out half the suspected code path. If the bug persists, it is in the other half.
git bisect does this automatically for regressions. Give it a known good commit and a known bad commit, and it walks you to the exact change that introduced the failure.
Read the stack trace completely
Most developers read the first line of a stack trace, assume they know the cause, and start editing. The useful information is often three or four frames down.
Read the entire trace. Find the last frame that is your own code. That is almost always where the fix belongs.
When you are stuck
- Explain the problem out loud. Rubber duck debugging works because articulating the problem forces you to structure it.
- Walk away for 20 minutes. The brain continues working on the problem during idle time.
- Ask for help early if the investigation is blocking other work. A 10-minute explanation to a colleague often produces the answer that two hours of solo investigation did not.
After the fix
Write a test that would have caught this bug. If you cannot write one, ask why not. If the answer is "the architecture makes it hard to test this path", the architecture is the next thing to address.