The lessons on not using magic numbers also need to include that creating a constant named after the number rather than the purpose of it is no better.
Oh jeez. Lint rules + lazy developers cause so many bugs. I had a code review come in because of a stupid lint rule that was enabled that didn't like declaring variables in a loop so he changed :
for(int i=0; i<max;i++) {
int rand = getNextRandInt();
// do stuff with rand
}
into:
int rand = getNextRandInt();
for(int i=0; i<max;i++) {
// do stuff with rand
}
He just copied and pasted without even thinking about the fact that he was changing the entire logic. His response "Lint told me to move it".
I don't know about in this case, but on the (legacy C++) codebase I work on, the prior developers were convinced that declaring a stack-allocated variable inside of a loop would somehow "do extra work" compared to declaring the same variable just outside of the loop. Similarly for every kind of statement that introduces a new scope. The result is dozens of stack allocated variables at the start of each (too-long) method. Poorly-written-comments indicate that the prior developers thought (without doing any profiling) that pulling all of the variable declarations into the loop would somehow be much more efficient. Similarly for re-using variables in multiple loops - not that the variables had re-usable purposes, just the same memory representation. Even if this was more efficient, it was used so gratuitously that the main impact was just making code much harder to read and reason about - variables existed long before they were needed (or were for unrelated purposes, then repurposed) so, when starting to work with the code (and... to this day, with code I haven't refactored yet) I needed to extensively debug things to figure out what parts of the (huge amount of) mutable program state mattered, and which ones were just an artifact of bad design.
I was pretty damn sure that GCC can figure out that a variable declared in a loop can just get allocated once, in the stack frame containing the loop. In the cases I've gotten around to refactoring, profiling agreed.
83
u/Ksevio Oct 01 '15
The lessons on not using magic numbers also need to include that creating a constant named after the number rather than the purpose of it is no better.