The Art of R Programming

(WallPaper) #1
Fixing a buggy program is a process of confirming, one by one,
that the many things youbelieveto be true about the code actually
aretrue. When you find that one of your assumptions isnottrue,
you have found a clue to the location (if not the exact nature) of
a bug.

Another way of saying this is, “Surprises are good!” For example, say you
have the following code:

x<-y^2+3*g(z,2)
w<-28
if(w+q>0)u<-1elsev<-10

Do you think the value of your variablexshould be 3 afterxis assigned?
Confirm it! Do you think theelsewill be executed, not theifon that third
line? Confirm it!
Eventually, one of these assertions that you are so sure of will turn out to
not confirm. Then you will have pinpointed the likely location of the error,
thus enabling you to focus on the nature of the error.

13.1.2 Start Small.....................................................


At least at the beginning of the debugging process, stick to small, simple test
cases. Working with large data objects may make it harder to think about the
problem.
Of course, you should eventually test your code on large, complicated
cases, but start small.

13.1.3 Debug in a Modular, Top-Down Manner..........................


Most good software developers agree that code should be written in a mod-
ular manner. Your first-level code should not be longer than, say, a dozen
lines, with much of it consisting of function calls. And those functions should
not be too lengthy and should call other functions if necessary. This makes
the code easier to organize during the writing stage and easier for others to
understand when it comes time for the code to be extended.
You should debug in a top-down manner, too. Suppose that you have set
the debug status of your functionf()(that is, you have calleddebug(f),tobe
explained shortly) andf()contains this line:

y <- g(x,8)

You should take an “innocent until proven guilty” approach tog().Do
notcalldebug(g)yet. Execute that line and see ifg()returns the value you
expect. If it does, then you’ve just avoided the time-consuming process of
single-stepping throughg().Ifg()returns the wrong value, then now is the
time to calldebug(g).

286 Chapter 13

Free download pdf