Re: A89: Re: A Address book With Some Real Problems


[Prev][Next][Index][Thread]

Re: A89: Re: A Address book With Some Real Problems




About globals:

There are definitely uses for them, but they are also easy to overuse.
Recently I wrote a program that needed an error log to be printed to the
screen. Since there were several functions that could generate an error and
no way to predict when an error might occur, I made the error log string
global.

About "magic numbers":

Very bad idea, for more reasons than just readability. They are confusing by
nature, of course. But just as important in many cases is the fact that if a
constant changes, you have to search through all of your code and find every
place you used it in order to update it. If you've declared it as a
constant, you only need to change it in one place. As an illustration of the
first point, I came across this code yesterday:

int s, m, h, d;

d = t/864000;
t -= d*864000;
h = t/36000;
t -= h*36000;
m = t/600;
t -= m*600;
s = t/10;
t -= s*10;

Any idea what it's doing? Poor variable naming is part of the problem, but
those ugly constants aren't helping. What if it were this instead:

const int T_PER_SEC = 10;
const int T_PER_MIN = T_PER_SEC * 60;
const int T_PER_HOUR = T_PER_MIN * 60;
const int T_PER_DAY = T_PER_HOUR * 24;

int secs, mins, hours, days;

days = t/T_PER_DAY;
t -= days*T_PER_DAY;
hours = t/T_PER_HOUR;
t -= hours*T_PER_HOUR;
mins = t/T_PER_MIN;
t -= mins*T_PER_MIN;
secs = t/T_PER_SEC;
t -= secs*T_PER_SEC;

Now it's fairly obvious what is happening, and to the compiler it's
identicall. It would help a little more to know that "t" refers to "tenths
of seconds". Unfortunately this doesn't illustrate the problem of needing to
change constants, since the number of tenths of seconds in a day stays
pretty much the same.

I'm a big advocate of following (most) proper coding practices, even if you
don't totally understand why. Someday you probably will understand, and in
the meantime you might actually be able to read your own code a week after
writing it. I know it seems like a minor issue to a beginner when you have
to study your code as you write it anyway, but later on you'll be cranking
the code out much quicker and you might not even recognize something you
wrote yesterday. But if you use good style, you'll at least understand it.

-Kevin