Chris said:
Eric Sosman wrote:
??
I know my code is not always to everybody's taste, but it has been quite a
while since someone last complained that it caused feelings of incipient
nausea...
-- chris
P.S. In case it isn't obvious: I'm not offended, just curious.
We're considering two alternative code snippets:
Alternative EQ:
if (++pos == bytes.length)
pos = 0;
Alternative GE:
if (++pos >= bytes.length)
pos = 0;
Neither can be deemed "correct" or "incorrect" in isolation, of
course: it is necessary to look at the rest of the code to see
how `pos' is computed and used. Nonetheless, the form of EQ
strongly suggests its purpose: the index `pos' is cycling through
the positions of the array `bytes'. In the rest of the code it
would be startling to find `pos' declared as a `float', or set
to Integer.MAX_VALUE, or set to a negative value (other than,
possibly, -1 at the very beginning), or advanced more than once
per iteration of the loop that almost certainly encloses the code.
We've seen things like EQ before, and we know how the form is used.
Alternative GE causes me to wonder whether there's a legitimate
way for `pos' to become large, how large it might become, and what
the significance of a large value might be. I wonder whether the
programmer who wrote GE instead of EQ might be guarding against
some devious pathway that could change `pos' before arriving at
this piece of code, and I start looking for that pathway. I also
find myself thinking that if `pos==bytes.length' cycles back to
zero, perhaps `pos==bytes.length+1' should cycle back to 1 instead
of zero, or `pos==bytes.length+n' should cycle back to n -- after
all, this is a form I've seen before, too, in situations like
searching through open-addressed hash tables.
So when I see alternative GE instead of EQ I start asking "Why?"
and this disrupts my reading of the code. Only a very little bit,
to be sure, since I've had many years' practice at reading code and
a tiny trivial matter like this one won't bother me very long.
One tiny final point: Java, unlike many languages I've used,
checks array indices for validity. Because of this, there might be
a very small advantage to using alternative EQ instead of GE, the
idea being that if there is in fact a bug somewhere that makes `pos'
large before arriving at the code snippet, GE will "throw a blanket"
over the bug if it executes before the bad `pos' value actually gets
used. EQ, on the other hand, will let the bad value survive to be
exposed by an ArrayIndexOutOfBoundsException, possibly leading to
earlier detection and repair of the programming error. Maybe.
Tempest in a teapot, really.