Chapter 13 of 15

Debugging

Be a scientist, not a superstitious monkey

Debugging is another skill that senior developers say new developers are really bad at. The number one way to be bad at debugging is to be superstitious.

Don’t change five things at once

You’ve found a bug. Something’s going wrong. So you think: “Well, I’ll change this thing. Maybe it’s that thing. That code looks a little bit wrong — I’ll replace it with something else.” You make five changes at once, run it, and…

Either it works or it doesn’t. But either way, you’re in trouble. You don’t know which change fixed the problem. You don’t know why it was broken. You don’t know what other things you’ve broken with your five changes. You’ve just shuffled the deck and hoped for the best.

Be methodical

The way to debug is methodically. Form a hypothesis about what’s going wrong. Change one thing. See if that fixes it. If yes, great — you understand the problem. If no, revert that change and try the next hypothesis.

If you change one thing after another after another without reverting, you still don’t know which change was important. Change one thing. Test. Revert if it didn’t help. Repeat.

Delete code you don’t understand

If you find code in a legacy application and you don’t know what it does, delete it. You’re going to discover one of two things:

  1. That code wasn’t necessary — great, you’ve made the application simpler and more maintainable.
  2. Something breaks — and now you know what that code was for.

Either way, you win. Don’t leave mysterious code in the codebase out of fear. But also: don’t commit code you don’t understand. Don’t superstitiously copy patterns from other parts of the codebase because they “look important.”

Do write code you don’t understand

This sounds contradictory, but it’s different. A lot of the time, you’re going to be exploring APIs and libraries to figure out how they work. Documentation will only tell you so much. The way you actually learn how an API works is by running stuff against it and seeing what happens.

The fastest way to do this is to use a REPL — the Read-Eval-Print Loop. In JavaScript, that’s the browser console or the Node.js REPL. You can paste in a line of code, hit enter, and immediately see what it does. The three minutes you used to spend writing a test script are down to five or ten seconds. That’s 10x programmer territory — not because you’re coding faster, but because you’re spending less time on things that aren’t coding.