2010-08-03

How to make debugging easier

本文系为组内NewsLetter创刊所写,属于“Experience Sharing”一节。本文不算是个正儿八经的东西,缺了点插图,多了些罗嗦。

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”

– Brian Kernighan

So, what is debugging?

“The process of identifying divergences between the intent and the implementation is known as debugging. It is hard to do this if the intent is not known.”

– Robert Love, “Linux Kernel Development”

Among citations about debugging, the above two are my favorite. I myself learned the following lessons and glad to share with you.

  1. Clean and simplicity is the most crucial elements for writing good software. Only with a clean interface and abstraction layer we can make our intention clear, thus easy for maintenance and debugging. This is essentially the first step toward reliable software.
  2. Write test code to express intention. Each test case is a precise definition of an interface, and they can help produce regression bugs when developers are in continuous integration or after refactoring. Update test case along with a bug fix.
  3. Test your code as soon/much as possible. Test cases mostly are dealing with logic defects, while there are other factors of good software: memory usage, code efficiency and security concerns etc. Use all the tools you know to test and profile your code, before its releasing to QA engineer, at least before its deploy in end-user environment.
  4. Make invisible things visible. Log crucial actions in your code. One of my tips for debugging static compiled language such as C/C++ is to add some debug functions in the code which is surrounded by #ifdef DEBUG and #endif. For example, if there is a ring buffer shared by multi-threads, and you can add an print_ringbuf(), and use “call print_ringbuf()” in GDB to dump it.
  5. Manage your code with a VCS tool. I personally prefer Hg and Git, since they provide a fast `grep’ command to lookup the whole repository. Also it’s easy and fast to do a diff between different change-sets or branches.

Last but not least, I’d like to say that do NOT rely on debugging techniques! Instead, we should try the best to write comprehensive software and avoid debugging. Imagine you will never have a debugger and “always program as if the next person who will maintain your code was a psychopath killer that knows where you live”. I believe it will make you a better programmer!

标签:

0 Comments:

发表评论

<< Home