P
Paul Lutus
Vincent said:In fact, those two codes look pretty much the same. This is a good
demonstration that while and for can be interchanged.
Since you can do that every time (use a for instead of a while, and a
while instead of a for),
But you can't do it every time. A for-loop has three clauses that are
carried out in a specific way. You can dispense with the three clauses,
making "for" resemble "while," but the reverse isn't true.
we need a "rule" to say when use which. I say
that in this case, since there is no incrementation part in the for loop,
we should use the while.
Seems reasonable, unless a case arises in which the control variable needs
to be kept local. In that case, it is the *effect* of using a for-loop, not
its appearance, that is more important.
Also, there are plenty of cases where a while-loop also involves
incrementation. I think the more basic difference is the for-loop's three
clauses, and times where this is the obvious choice.
I make one exception to this rule (but hell... if there were no exception,
it wouldnt be a rule, would it? ) for iterators: in java, the
incrementation is done in the first line of the body part of the loop, but
I still use for because I'm used to iterating data structures with a for
loop
I can't agree more with you.
I would not say that... I understand the necessity to have a loop that
decides to exit in the middle of its body.
It is best avoided, replaced by something that exits in a way easy to
visualize, otherwise the programmer may picture the algorithm in a way at
odds with reality.
The condition of your solution
(which is also mine since I do use the same construction when this problem
arise) is not a pure condition: it actually does things, and this may also
be considered as a hack.
Only if it can be replaced with something better. But it can't. In any case,
there is no reason to avoid actions along with tests if that is the most
efficient arrangement.
What if the code we had to launch before the test
was two lines long?
In that case I would call a method in order to maintain the structure of the
while loop.
I don't know what I prefer between writing a small function to handle that
(that does the code and return whether there is something to be treated)
or the while(true)/break solution...
The former meets the requirement to break actions up into logical units. The
latter IMHO is an acknowledgment of defeat.