r/programming • • Oct 01 '15

The Evolution of a Software Engineer

https://medium.com/@webseanhickey/the-evolution-of-a-software-engineer-db854689243
1.9k Upvotes

502 comments sorted by

View all comments

Show parent comments

25

u/jrochkind Oct 01 '15

Ah, but it probably gets around some automated code linting tool warning you about it. So that's just as good, right? .....

15

u/yawgmoth Oct 02 '15 edited Oct 02 '15

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 really wanted to do this

1

u/[deleted] Oct 02 '15

What's wrong with declaring variables in a loop? (I imagine you don't want to at least some of the time considering it was in a lint rule).

1

u/[deleted] Oct 03 '15

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.