// using while
int len;
while((len = inputStream.read(buffer)) > 0) {
bout.write(buffer, 0, len);
}
// using for
for(int len;(len = inputStream.read(buffer)) > 0
{
bout.write(buffer, 0, len);
}
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), 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.
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
In any case, the problem with those versions that duplicate one line of
code
is that there is a duplicate line of code, something professional code
administrators try to avoid at all costs.
I can't agree more with you.
The problem with "while(true)" should be obvious to all -- it is a hack,
as
is the use of "break" to get around the original hack.
I would not say that... I understand the necessity to have a loop that
decides to exit in the middle of its body. 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. What if the code we had to launch before the test
was two lines long?
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...