6.6. How to Avoid Debugging¶
While debugging is an unavoidable part of programming, you can reduce the number of bugs you encounter by working carefully.
6.6.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 the code will run.
6.6.2. Keep It Working¶
Once you have a small part of your program working, the next step is to figure out something small 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 that was 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.
Get something working and keep it working.
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.