free hit counter

Thursday, February 14, 2008

comp sci 101 practices realy do work

They teach all kinds of maxims in your first programming class: no magic numbers, no gotos, no globals, etc.

It's still amazing how many people still violate these maxims though. Today I saw further evidence supporting my favorite of these maxims: no magic numbers.

consider the call to a wait function when reading an accelerometer:

It would have been only slightly less clear, but by no means unintelligible to call:

And clarity could have been fixed if the function were named differently:

But two months after I originally wrote this code, and several slight revisions by another developer later, we found that .08% of accelerometer samples were getting corrupted because we needed to wait a little longer than the 200us the accelerometer datasheet recommends.

This is when the compiler and the no magic numbers maxim helped me avoid a stupid error. You see, I changed the #define to be:
#define wait_225_usecs 225

Unbeknownst to me, at another place in the same file someone else was sampling the accelerometer using the wait_200_usecs constant. Had they both been magic numbers, I might have only fixed the error in once place.



Post a Comment

<< Home