Chapter 2. Tips on Walking Through Code
This book's goal is to improve your ability to find bugs in code. Before you get to the actual code samples, this chapter offers advice on how to read code. The intent is not to provide a complete primer on debugging software, but to give you background information that will be useful when you look at the problems in the rest of this book.
In his paper, "Tales of Debugging from the Front Lines," Marc Eisenstadt discusses different ways in which bugs can be found. One of them is what he calls "gather data," which is to walk through the code in the debugger, add wrapper code, insert print statement, and so on. This can be a useful way to debug code, and in many cases, it is appropriate.
However, the problems in this book do not lend themselves to being solved by gathering data, because there is no data to gather. The programs are printed on a page and are meant to be debugged that way. You could type them into a computer and execute them if you wanted to, but that would defeat the purpose of this book.
The goal of the book is to have you debug programs by what Eisenstadt calls inspeculation, which he describes as "a hybrid of 'inspection' (code inspection), 'simulation' (hand-simulation), and 'speculation'. . . . In other words, [programmers] either go away and think about something else for a while, or else spend a lot of time reading through the code and thinking about it, possibly hand-simulating an execution run. The point is that this family of techniques does not involve any experimentation or data gathering, but rather involves 'thinking about' the code."
Archimedes, a mathematician who lived in the third-century B.C., was said to have reacted to his realization that the buoyancy of an object was related to the weight of fluid it displaced by running through the streets shouting, "Eureka!," which means "I have found it" in Greek. Archimedes was getting into his bath, watching water spill over the edge as his body displaced it, when he had his flash of insight. Finding bugs in code can be like that; all of a sudden, something clicks in your brain and you have your own "Eureka!" moment (running through the streets is optional).
This chapter presents a series of steps that can be followed when you walk through code. It is often not necessary to follow all the steps; at any point, the reason for the bug may suddenly pop into your mind, even if you are not directly considering the code that contains the bug. But, if that doesn't happen along the way, hopefully by the time you finish the final step, the bug will have revealed itself.
The steps are as follows:
- 1. Split the code into sections with goals.
- 2. Identify the meaning of each variable.
- 3. Look for known "gotchas."
- 4. Choose inputs for walkthroughs.
- 5. Walk through each section.
These steps are discussed in more detail in the following sections.
|