Re: How would I rewrite this to satisfy the code checker?
On Nov 5, 12:59 am, Roedy Green <see_webs...@mindprod.com.invalid>
wrote:
On Wed, 4 Nov 2009 13:06:20 -0800 (PST), laredotornado
<laredotorn...@zipmail.com> wrote, quoted or indirectly quoted someone
who said :
while ((line = reader.readLine()) != null) {
stringBuf.append(line + "\n");
}
[code edited for appearance]
saying, "Avoid assignments in operands". How would I rewrite the
while loop to make this error go away but achieve the same
functionality?
That code is fine. There is really no other way to do it. However in
general it is confusing to newbies if you write code of the form:
x = ( a = b ); // = assignment embedded in expression.
as opposed to
x = ( a == b );
--
Roedy Green Canadian Mind Productshttp://mindprod.com
An example (complete and annotated) is worth 1000 lines of BNF.
The problem with this idiom for me is that you have a choice of either
having a statement that has side effects, e.g., the original code, or
you need to duplicate the read statement. While both of these are
legal I don't like either. They both seem inelegant. Using the for
statement as Lew suggested at least makes sure that the two reads are
close together. This idiom is pretty common and I wonder if it's
worth considering a little bit of syntax that would allow (imho)
cleaner code.
Perhaps something equivalent to the for loop where the action that
takes place at the bottom of the loop in a standard for loop takes
place at the top of the loop. I.e.,
for (a; b; c) {d}
is equivalent to
{
a;
while (b) {
d;
c;
}
}
If we extended the while loop where
while(a; b; c) {d}
is rendered as
{
a;
while (1) {
b;
if (c) {
d;
} else {
break;
}
}
}
Then the original request becomes
while(; line=reader.readLine(); line != null) {
...
}
which avoids both the statement with side effects and duplication
of the readLine().
Of with all three clauses
while (Reader r = getReader(); line=r.readLine(); line != null) {
I think I would use such this rather often were it available. Has
such a construct been implemented in other languages or proposed for
Java?
Regards,
Tom McGlynn