Chris said:
I disagree with you on this for several reasons.
1. You way takes more lines of code, therefore more places to make
mistakes.
We are all entitled to our opinions, but I am from the school that says,
even if it is more lines, if the intent is clearer the that means it is
easier to maintain and fix in the future.
2. For loops are to count a number of known iterations, which is what he
has. The for loop has a set exit time. If it didn't, then it would just
be like a while loop. You will notice in your untested code, you would
loop endlessly if the item is never found. Yes, you could add another
check to make sure it doesn't, but there again, your making the code more
complex for no benefit.
This was the exact reason for my warning... "Warning.. not tested... off the
top of my head code..." It was off the cuff, done in the news editor, not
the code editor, not compiled or tested, and it was 12:21am...
Yes, you have a defined number of things to loop through, but the intent of
the code is not to always run that number of times. The intent is to look
through as many as needed and stop looking when the one you look for is
found. The for loop is analogous to looking through a deck of 52 cards
looking for the ace of spades and even if you find it on the third card you
keep looking. Yes, you can exit the for loop early, but to me that induces
the chance that if the code needs to be changed in the future errors might
creep in.
I am also a firm believer in the idiom of single exit points for functions.
I hate people that do things like this:
Public Function Foo(thingToWatch) as Boolean
'Looks for thing one and returns True when found
Select Case thingToWatch
Case ThingOne
return True
Case ThingTwo
return False
Case Default
return False
End Select
End Function
To me, exiting a for loop is the same nasty looking thing.
3. You give no reason why it is bad to exit the loop ahead of time.
Boy I tell you the web has let me down on this one. I have had several
documents over the years that have documented 'proper' styles for looping
structures and I have adopted them. This was even a very nitpicky area for
my teachers in college. Looking at the possible exit points in the code,
execution starts at the top and flows downwards. Decision statements can
branch out of a structure, loops simply repeat things. Decisions structures
branch, loops iterate and let the code flow.
Be damned if I can find a reference that is 'webable' right now...
Again, I guess it is more of a matter of taste and style.