"Debugging" refers to the process of finding and fixing errors, or "bugs" in a program. No program (except perhaps the most trivial) ever works correctly the first time. Even experienced programmers write code with bugs, and for this reason debugging skills are just as important as coding skills.
Note that debugging is not necessarily the same thing as using a debugger. A debugger is one tool for debugging, but you can also debug your program just by inserting print statements in it.
The most important thing you can do to make your code easier to debug is to test it often. Immediately after writing a section of code, you should run it and check that it's working correctly. The main reason is that it's much easier to debug a piece of code that you've just written (and is fresh in your mind) than something you wrote a while ago.
Also, testing each piece of code individually is much better than testing everything together, at the end. The reason is that it makes it easier to narrow down where problems are coming from.
Print things out
One great debugging strategy is printing out the values your program is dealing with. For example, if you are reading data from a file, print it out after reading it in. That way you make sure that values are what you expect them to be.
Don't make assumptions
Oftentimes programmers will think "well that can't be the problem" and then somehow it is. When debugging, try not to come to a conclusion as to the cause of the problem before you're sure.
For example, if you have a program that reads data from the user, then does some processing on it, one might assume that the processing is the reason for the wrong answers. But maybe the method that's reading input has a problem, like returning the data formatted in a way we don't expect.
Don't just stare at the code
Debugging should be an active process where you run your program, add print statements or make changes, and then run it again. Problems are very rarely fixed by just looking at the code and thinking about it.
The first step in using IntelliJ's debugger is to create a break point. This is a line of code that the debugger will stop at when it gets to it. To make a break point, you can click on the column to the right of your code, on the line you want to stop at:
You can then run your program with the debugger by choosing "Debug" from the Run menu. Your program will then stop when it gets to one of your breakpoints. You can then inspect the values of different variables. The debug window contains a view of the stack. You can click on this to see variables in your stack frames:
Once we are at a break point like this, we can then step through the code using the following commands:
The debugger removes the need to add lots of print statements to your code. You can run through it and see the values of all your variables as the program runs.
Copyright © 2023 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.