Re: For Loops and Variables
- From: "Chris Uppal" <chris.uppal@xxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 6 Apr 2007 09:23:57 +0100
Jason Cavett wrote:
The discussion was that the use of the variable "i" was not good as it
should be named something that means something (arrayCounter or
whatever) so it is easier to understand the code.
Like the others, I see nothing wrong with using i for a loop index, and good
reasons to prefer that common idiom in many cases (the fact that it /is/ a
common idiom not least amongst them).
It might be worth saying a bit about /why/ it is acceptable, although it
appears to break the general rule about preferring communicative names.
Somewhat less than half the point is that there is no real need for long
identifiers here -- that's to say that a (very) short identifier is just as
communicative as a long one in this context. And -- all things being equal --
short identifiers are to be preferred over long ones. (The qualification, "all
things being equal" is, of course, /vital/) In any sensible code, the array
index's scope is limited to the loop over the array -- which is a very limited
scope, so the amount of information the identifier must convey is similarly
limited. There is nothing for it to say that is not immediately evident from
the context in which it appears, simply because it only /exists/ in that
immediate context.
The bigger part of the point is that there (usually) is nothing much for the
identifier to communicate /anyway/. It is an array index, and once you've said
that, there isn't (usually) anything else to add. The meaning (usually) lies
in the thing found in the array, at the index, not in the index itself.
The repeated "(usually)" in the above are because of occasional exceptions to
the rule. Perhaps the most common (which Gordon has already touched on) is
when you are considering row/column indexes in 2D arrays. In such cases it can
be sensible to keep it clear whether an index varies over rows or columns.
That is especially true if you are also messing with X/Y coordinates in the
same code (such as painting a grid), since the normal English word order for
rows and columns ("row" then "column" ;-) is inconsistent with that for "x" and
"y" -- which can easily turn the code into a nightmare unless you take steps to
make the relationships explicit. There are other examples, but that one is
probably sufficient...
-- chris
.
- References:
- For Loops and Variables
- From: Jason Cavett
- For Loops and Variables
- Prev by Date: Re: Sequence of calling super's constructor in Java
- Next by Date: Re: How to insert CDATA in an XmlBean tag!
- Previous by thread: Re: For Loops and Variables
- Next by thread: Wierd ArrayIndexOutOfBounds
- Index(es):
Relevant Pages
|