Debugging best practices
There are certain things you can do with your code that will make debugging a lot easier when errors occur.
This tutorial focuses on:
- Indent your code
- Use a lot of comments
- Breakdown into smaller parts
- Maintain neatness and readability
Indent your code
When your code is indented, it will be easier to find the error because you'll have a much better idea of how things in the code are connected. You will be able to go through your code faster and when you have an error in one block of code you will easily know where that block of code begins and where it ends.
When you indent your code, not only will it be easier to find errors but it will also look cleaner and be easier to read and work with (for you and anyone else working on it).
Use a lot of comments
Using lots of comments, you'll be able to quickly know what the code is supposed to do which makes it much easier to figure out why it's not working as intended.
In the above example we are trying to add 9 + 10 and multiply the result by 9. Instead, 9 is multiplied by 9 and 10 is added to the result. But you wouldn't know that since there are no comments.
Thanks to the comments we can tell the code is supposed to print out 171. But it doesn't. It prints out 91. Now we know what the code is trying to do and what the error is and now we can fix it.
What is in the parentheses gets evaluated first. That's how we are able to print out the right value.
Breakdown into smaller parts
Complex things consist of many simple parts. If you have a large segment of code try breaking it down into smaller parts. For example, if you have a function with 120 lines of code consider breaking it down into a few different functions. This way it will be easier to track down the error when there is one since you will know that the error is located in one of the smaller functions as opposed to having to go through one big chunk of code.
Maintain neatness and readability
The more neat and readable your code is, the easier it will be to go through it and find errors.
To maintain neatness and readability:
- Indent your code
- Have a lot of comments
- Have consistent spacing (don't compress everything together, have some line breaks and extra space where you need it)
- Give your functions, variables, and other things that have names meaningful names. It's much easier to figure out what something is supposed to do in the code when it has a meaningful name.
If you feel you have too much code, focus on how you can shorten it (while still retaining the same functionality). Don't do in 20 lines of code what you can do in 5 lines. The less code you have, the less time you will need to find errors.