Re: For Loops and Variables
- From: Eric Sosman <Eric.Sosman@xxxxxxx>
- Date: Thu, 05 Apr 2007 15:49:04 -0400
Jason Cavett wrote On 04/05/07 11:47,:
This was a discussion my co-worker and I had awhile back and I was
curious what the group thought.
for(int i=0; i < someValue; i++) {
// do stuff
}
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. The reverse
argument was that using the "i" variable as a counter was an okay
practice and it is alright as long as it is the only variable doing
this (all other variables are well named). Convenience of typing "i"
versus "someLongVariableName" was the argument on this side.
I'm just curious what everybody here thinks about this. Are there any
standards on this topic?
P.S. I purposely didn't state what my position was.
P.P.S. Both parties agreed that meaningful variables were a good thing
overall.
There are two kinds of consumers of source code: compilers
and people. Compilers have a good memory for detail, and don't
care what names you use: If all the variables were named l
and l1 and ll and l1l and ll1 they'd be perfectly content. So
the selection of variable names should be motivated solely by
the rather different cognitive needs of flesh-and-blood readers.
When I myself read code, it seems easier to read short names
than long ones. On the other hand, short names can be cryptic;
my reading is not aided if I need to keep interrupting it to go
look for a comment on a variable declaration a hundred lines
distant. I've found that a pretty reasonable balance is struck
if I let the length of a variable name depend on the "size" of
its scope. I'll use short names for variables that are declared,
used, and abandoned in a "small" region of code, and longer names
for variables with more "staying power" whose visibility and
significance extend over wider spans.
(Corollary: method and field names have significance
throughout an entire class and sometimes even beyond it,
hence their names should always be descriptive.)
So, what category fits loop indices? Well, it depends on
the loop -- that is, on how "big" the `// do stuff' is. For
half a dozen lines `i' is fine; for half a hundred you'd want
`fragmentIndex'; for half a thousand consider refactoring.
It works for me. YMMV.
--
Eric.Sosman@xxxxxxx
.
- Follow-Ups:
- Re: For Loops and Variables
- From: Daniel Pitts
- Re: For Loops and Variables
- From: Patricia Shanahan
- Re: For Loops and Variables
- From: Gordon Beaton
- Re: For Loops and Variables
- From: Jason Cavett
- Re: For Loops and Variables
- 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: XML Parsing Troubles
- Previous by thread: Re: For Loops and Variables
- Next by thread: Re: For Loops and Variables
- Index(es):