One of the basic programming techniques that I try to use regularly is to step through any new code I write in the debugger. A lot of developers tend to only use the debugger for finding problems with code, but by the time you have a bug, I believe you've waited too long. Instead, as soon as you've written some new code, set a breakpoint at the start of it, and then run your application. When you hit the breakpoint, step through the code, asking yourself the following questions:
- Is the flow correct for the conditions? That is, are all the conditional statements (if, while, for, etc) branching correctly based on the inputs? If not, why?
- Are your variables getting set correctly? Watch the values of all local variables and parameters and make sure they match what you expected when you wrote the new code.
- Are you able to make all (or almost all) branches of your code execute? Make sure you can hit all new lines of code, even if it takes several runs. There may be some error-handling or exception catching code that you may not be able to step into without some test code or other jumping through hoops, but do the best you can.
- If it is a new method, does the return value match what you were expecting? Make sure you test all conditions possible.
I've found that I produce better quality code when I do this often. A lot of people recommend unit tests, and those are great when you can use them, but for some types of code, like UI code, they are either difficult or impossible to implement. Stepping through with a debugger is easy and doesn't take much more time than running your code normally. I've discovered errors or omissions quite a few times by doing this.
No comments:
Post a Comment