Have you ever asked a question of a friend, co-worker or teacher only to stop yourself halfway through an realize--"I got it!"
Well, there's actually a name for that in programming: Rubber Ducking
The name comes from an anecdote in The Pragmatic Programmer in which a programmer would carry a rubber duck around with them and debug their code by explaining it to the duck.
Sound crazy? Here's why works:
Why Rubber Ducking Works
Gaining a New Perspective
Articulating your problem out loud has so many advantages. First of all, it forces you to take a step back from your code. When you explain it to someone (or something) else, you look at it from a different perspective. This can bring you to a new level of understanding that just might reveal what the problem is.
Understanding the Problem
By explaining your problem out loud to the rubber duck, you have to articulate:
A. What your program is _supposed_ to do (i.e. the desired behavior)
B. What your program is _actually doing_
The process of debugging our code is really just the journey from A to B. By stating these two things out loud, we can often see exactly what we're missing to build the bridge from actual to expected behavior.
The Aha! Principle
You are not smarter than Albert Einstein. In a 1922 lecture on the Theory of Relativity, Einstein related the following story:
Albert Einstein was describing his very own brush with the "Aha!" effect. The idea that, by talking through your problem you can be visited by a sudden flash of insight. Sometimes, all it takes is explaining the issue to someone else.
How to Rubber Duck
- Get a rubber duck! Does it have to be a rubber duck, you might be wondering? I recommend using any small ridiculous object that you can keep on your desk. In a pitch, a medium-sized, ridiculous dog might do.
- Talk to it! This part isn't as easy as it seems. Try the following:
- First, explain the desired behavior of your program. What should your program do?
- Then, explain the actual behavior of your program. What is your program doing that is different from the desired behavior?
- Lastly, read your code aloud line by line. After each line or group of lines, stop and explain to the duck what you think these lines of code do.
And before you know it, you and your new imaginary friend will be squashing bugs like a boss.