Debugging 191
11 Debugging
“ e diff erence between the right word and the almost right word
is the diff erence between lightning and a lightning bug. ”
—Mark Twain
“ L’appétit vient en mangeant. ”
— e French
Bugs happen.
Five minutes ago, your code was working perfectly and you swear, all you did was change the color of
some object! But now, when the spaceship hits the asteroid, it doesn’t spin any more. But it was totally
spinning fi ve minutes ago! And your friend agrees: “ Yeah, I saw it spin. at was cool. ” e rotate( )
function is there. What happened? It should work. is makes no sense at all! e computer is probably
broken. Yeah. Yeah . It is defi nitely the computer’s fault.
No matter how much time you spend studying computer science, reading programming books, or playing
audio recordings of code while you sleep hoping it will soak in that way, there is just no way to avoid
getting stuck on a bug.
It can be really frustrating.
A bug is any defect in a program. Sometimes it is obvious that you have a bug; your sketch will quit (or
not run at all) and display an error in the message console. ese types of bugs can be caused by simple
typos, variables that were never initialized, looking for an element in an array that doesn’t exist, and so on.
For some additional clues on “ error ” bugs, take a look at the Appendix on errors at the end of this book.
Bugs can also be more sinister and mysterious. If your Processing sketch does not function the way you
intended it to, you have a bug. In this case, your sketch might run without producing any errors in the
message console. Finding this type of bug is more diffi cult since it will not necessarily be as obvious
where to start looking in the code.
In this chapter, we will discuss a few basic strategies for fi xing bugs ( “ debugging ” ) with Processing .
11.1 Tip #1: Take a break.
Seriously. Go away from your computer. Sleep. Go jogging. Eat an orange. Play scrabble. Do something
other than working on your code. I can’t tell you how many times I have stared at my code for hours
unable to fi x it, only to wake up the next morning and solve the problem in fi ve minutes .
11.2 Tip #2: Get another human being involved.
Talk through the problem with a friend. e process of showing your code to another programmer (or
nonprogrammer, even) and walking through the logic out loud will often reveal the bug. In many cases, it
is something obvious that you did not see because you know your code so well. e process of explaining
it to someone else, however, forces you to go through the code more slowly. If you do not have a friend
nearby, you can also do this out loud to yourself. Yes, you will look silly, but it helps.