In a previous installment, I discussed the quality of English in comments, arguing that the quality of comments influences the reader’s judgment on the quality of the code as well.
That’s not the only thing that can make code harder or easier to understand. Today (anyway, at the time of writing), I was working on something where arbitrary-looking constants would constantly come up. I mean, constants that you wouldn’t know where they’re from unless there’s a comment. A clear comment. Let’s see some of those.
Can you guess the following constants?
Think a while and see if you can find a short expression for these constants. The answers are a bit further down. No peeking!
Some of those are easy to find, but even when you can find the original “natural expression” for the constant, you may still not know where it’s from. If you see something like:
... s=1.0/sqrt(n); v += 2.199272222*u; ...
you’d be hard-pressed to figure out where the constant is from. However, if you read
... s=1.0/sqrt(n); ... // solving 4pi/n = 3sqrt(3)/2 s^2 // for s (finding the side s of an hexagon // with surface 4pi/n), we find that // // s= sqrt( (8 pi) / (3sqrt(3) n) ) // v += 2.199272222*s*u; ...
it’s already much better. Of course, the code now includes a rather lengthy comment on how this formula is derived. Maybe if we added where it’s from, possibly a reference to a paper where it was used, it would be complete. In the above, it’s easy to google or use Wikipedia to find that the length of the side of a regular hexagon occupying of the surface of a unit sphere gives the formula above. Let us pretend that, in this context, it makes perfect sense to use this derivation.
Plugging an “efficient” constant like in the middle of the source code is only machine efficient, not efficient in absolute terms. It greatly reduces maintainability as the next programmer that will work on this program may, or may not, know about the derivation of this constant and just plug some other “random” value. (And I have seen this. For real. “bah! some random number! let us use 2 instead. 2’s big enough.” Epic facepalm moment, I tell you.). It also reduces maintainability because if, for some reason, a pentagon is needed, say, the constant must be replaced by some other constant but the next programmer may, or may not, be able to figure out how to do so. With the last comment, he will at least understand what to do.
I hope you tried hard. Anyway, here are the answers:
where is log-base-2.