10.5. How To Avoid Debugging¶
You cannot avoid debugging. Humans make mistakes, so there will always be bugs to fix.
However, you CAN reduce the number of bugs in your code by working carefully.
10.5.1. Start Small¶
This is probably the best piece of advice for programmers at every level. It can be tempting to sit down and write an entire program all at once. However, this leaves a large number of possibilities when the program does not work. The errors could be hiding anywhere in the code. The more code, the more possibilities exist. Where to start? How to figure out what went wrong?
When you start work on a large program, break the process down into smaller steps! Begin coding one very small part—even if that’s just 2 lines of code. Then make sure the program runs properly before adding the next small part.
Regularly running your code is quick and easy, and doing so gives you immediate feedback about how well the code runs.
10.5.2. Keep It Working¶
Once you have a small part of your program working, the next step is to figure out a new small thing to add to it. If you keep adding small pieces to the program, one at a time, it is much easier to figure out what went wrong. Any error that occurs was almost certainly introduced by the last line or two of code you added. Less new code makes it easier to locate the problem.
Here is your new mantra:
Get something working and keep it working.
Repeat this throughout your career as a programmer. It’s a great way to avoid frustration and reduce stress while creating amazing (and working) code.
Research has shown that with every little success, your brain releases a tiny bit of a chemical that makes you happy. So you can keep yourself happy and make programming more enjoyable by creating lots of small victories for yourself.
10.5.3. Talk to a Duck¶
When you get stuck and just can’t seem to find the bug, take a break. Let your brain rest for a few minutes.
Once your break is over, look at your code again and describe the problem OUT LOUD. You can talk to your screen, a friend, your parents, a rubber duck, a stuffed animal, your hand, etc. It does not matter who or what you talk to. The act of describing the issue OUT LOUD (as well as what you have done to try to fix it) lights up different parts of your brain.
More often than you expect, verbally describing an error with your code produces an “Ah ha” moment, and you think of something new to try.
There is NO shame in asking for help. The duck won’t judge.
10.5.4. Practice Makes Better¶
As you create more code, you will get faster and better at finding, fixing, and avoiding bugs.
Here are some links that offer advice for some common issues: