I had a huge discussion over this exact same issue just a few days ago. I remember when going through coding classes, many teachers would tell me to “code defensively”. I think I have a grasp now on what they were trying to accomplish. They were trying to prevent code from reaching this state in where you cause 2 new bugs for each new piece of code you write. However, these techniques probably aren’t common knowledge, so I’ll just lay them out here…
Code in small pieces
Try to keep away from lengthy code sessions. Not only is it a risk, (we can lose all of our work if the power goes out or you accidently click close), but it also increases chances for errors and makes it harder to trace bugs. Save often and compile often.
Comment more
As programmers, we usually don’t comment enough. The problem isn’t apparent when you are working on something daily, but when you come back to it after a while you almost get to the point where you have to re-learn your own code. The worst side-effect about it is, you forget what features you already have. You can easily start creating bugs for no reason.
Write code legible
Keep the code organized and in modules if possible. It saves a lot of headache in the long run, and making it modular for large projects really gives programming a “tool set” feel. It feels good to be able to use code in multiple places. Disorganized code is a recipe for bugs.
Those techniques are good for prevention, but what about when I have errors anyway…
It depends on the bug. Usually, if I’m dealing with a logic error I always use the debugger or the JUnit tests to try and solve it. Sometimes you need to keep a good track of what your variables are doing to help you solve a problem. If I’m lazy and I think the logic error is in a specific spot, I’ll use print statements. If the error has to do with performance, I always depend on the profiler. If the error is syntax, I just solely use the debugger.
Having a plan is always good for programming. Even with very high amounts of documentation, it is still very possible to have bugs. You have to actively watch over your code to make sure you aren’t creating issues further up the chain. As said earlier in the thread, 2/3 of programming is just problem solving. (I guess the other 1/3 is creating the problems
)