When reviewing, I sometimes encounter this kind of loop:
i = begin
while ( i != end ) {
// ... do stuff
if ( i == end-1 (the one-but-last element) ) {
... do other stuff
}
increment i
}
Then I ask the question: would you write this?
i = begin
mid = ( end - begin ) / 2 // (the middle element)
while ( i != end ) {
// ... do stuff
if ( i > mid ) {
... do other stuff
}
increment i
}
In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements:
i = begin
mid = ( end - begin ) / 2 //(the middle element)
while ( i != mid ) {
// ... do stuff
increment i
}
while ( i != end ) {
// ... do stuff
// ... do other stuff
increment i
}
Now I even saw a question on SO on how to write the if
-clause in a nice way... And I got sad: something isn't right here.
Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time?
I came to a realization that when I put special cases in a for loop, I'm usually being too clever for my own good.
I prefer to simply, exclude the element from the loop and give a spearate treatment outside the loop
For eg: Lets consider the case of EOF
Of course, special-casing things in a loop which can be pulled out is silly. I wouldn't duplicate the do_stuff either though; I'd either put it in a function or a macro so I don't copy-paste code.
The special case should be done outside the loop if it is only to be performed once.
However, there may be an index or some other variable(s) that are just easier to keep inside the loop due to scoping. There may also be a contextual reason for keeping all the operations on the datastructure together inside the loop control structure, though I think that is a weak argument on its own.
Its just about using it as per need and convenience. There is as such no mentions to treat elements equally and there is certainly no harm clubbing the features which language provides.
I think you have it entirely nailed. Most people fall into the trap of including conditional branches in loops, when they could do them outside: which is simply faster.
For example:
And the middle case you described is just plain nasty. Imagine if that code grows and needs to be refactored into different methods.
Unless you are parsing XML <grin> loops should be kept as simple and concise as possible.