I spend a lot of time in various IRC channels answering questions and helping out, and one recurring theme that pops up again and again is people not knowing what to do when things go wrong. Whether it be a simple error or a logical mixup, people often lack the tools or processes to figure things out. So I thought I would share how I approach errors and problems. I like to think of error and debugging techniques as layers or levels of defense. I go through each layer until I reach the end.
Errors and error messages
Errors happen but the most important thing to do is to read them. Often errors have lots of valuable information, such as the type of error, a message, and what line & file the error came from. So reading and sometimes re-reading error messages is the first step to solving errors. Suppressing or otherwise hiding errors, does not fix them. It just delays the inevitable implosion of garbage code.
Sometimes re-reading errors doesn’t make them any clearer, at this point I turn to Uncle G and put in the generic parts of my error and see what comes back, usually I get something good and am able to resolve the issue.
Sprinkle some output
When reading an error message isn’t enough the next level of error defense is some dumps. I’m a huge fan of
var_dump() These functions are invaluable for finding out what’s going on inside your code. Often sprinkling some
debug() here and there will give me enough information to get the issue solved.
Isolate the problem in a test case
debug() doesn’t save me, I start writing more test cases. I normally write a fair number of test cases while writing code. But when faced with an extra gnarly problem I write even more test cases. Using test cases helps me isolate the issue and narrow down the where and how the issue is being caused. Test cases have the added bonus of living beyond my current session, and helping to prevent the same problem later. If I can’t reproduce the issue in a test case, I’m either looking in the wrong place or there is some extra funky junk in my code.
Break out the GDBp and other big guns
If an involved session of debugging doesn’t get the issue fixed, its time for coffee/water. I find when all my tools and techniques fail me, its usually me not seeing the trees in the forest. A five minute respite often gives me the break I need to come back with fresh eyes and see the problem staring me in the face.
So those are the common steps I take when I have an error or issue in my code, what are yours?