views:

365

answers:

15

Code Complete book suggested, it is a good practice to use meaningful names for loop control variables.

For example:

  for(int month=0; month < MONTHS_PER_YEAR; month++){

    // processing

  }

Instead of single letters for example

 for(int i=0; i < MONTHS_PER_YEAR; i++){

  // processing

 }

I follow this practice and use meaningful names for each loop control variables. Recently one of my code reviews was failed due to above practice. My code reviewer said “You should use short concise variable name such as I, j for loop control variable”

What do you think?

+9  A: 

I think that it depends on the context. In a loop where the variable will be used to index an array you should use short letters such as i,j,k, but in your case month is better as it is clearer.

Darin Dimitrov
The code given is not enough to know if it is clearer. What needs to be clear is code inside the body of the loop. If all the loops in the rest of the codebase use i,j, and k, can you say that the second sample is unclear?
Mocky
@Mocky: I agree.. there's no way to know if month is clearer than i
0A0D
+4  A: 

To me, it's personal preference to use i,j,k for loop iterators. The comparison value usually something explicit like MONTHS_IN_YEAR or DAYS_IN_MONTH. Code Complete is a good book, but you don't have to follow it completely. I don't think you should of gotten bad marks for not using i,j, or k. Maybe in the future, a better suggestion would be to use monthIndex instead of month. I haven't seen the array, but maybe because it comes out as

month[month]

It does not look right and thus

month[monthIndex]

or month[i], would look better.

0A0D
+1  A: 

I'd say it depends on what's inside the block. If it's a short block and very obvious usage e.g. looping on an array of chars 'i' suffices.

If you have more code inside the block and that can lead to ambiguities, use a more meaningful name.

Ariel
+1  A: 

The variable names are only for developer\maintainer of the code. The compiler anyways don't use them for any optimization based on the name, so short and concise variable name has no advantages compared to meaningful names.

Most of the time when you are looping through array\vector\list using index then (i, j, k) look simple to use. You should use the appropriate variable name based on the context. In your case month suits.

aJ
Never had the experience like "damn, was `i` the _row_ or the _column_ in this matrix?"... It is argued (in the same Code Complete) that sometimes the bigger cost of a software product is the time spent by developers trying to figure out the meaning of `i`, `j` and `k` in swiftly written loop constructs. The compiler doesn't really care, so doesn't count.
xtofl
+1  A: 

Like Darin says, it depends on the context. In general though, the more specific you name your variables, the better the readability of your code. Thus, in your example, I would go with the first option. I only use variable names like i if I'm just looping through the index of an array (e.g. its length) and that itself doesn't have any other meaning.

I would explain to your reviewer that though it may depend on the context, saying that you should always user short concise variable names is not a good practice in itself. Show him an example where using good variable names makes the context much clearer.

Razzie
A: 

I guess it depend very much on your personal/company code guidelines. I still use variables like i,z,x but at my girlfriends company you would get into trouble for doing so. But meaningful names can never be wrong.

Holli
+1  A: 

Using i,j, and k as loop variable names is an idiom. It is an idiom so common that it leads to instant recognizability of the variable and its significance. The meaning is added to them by virtue of the fact that they always represent loop variables. If you know what you are looking at the moment you see the name, that is meaningful. The meaningful names concept goes hand in hand with the principle of least surprise.

Using a meaningful name for a loop variable may aid you personally in your own code, but when others need to read your code it may not help them. Simple things done in simple and expected ways can be more helpful.

If loop complexity makes i,j, and k undesirable a refactoring is probably in order rather than breaking the idiom.

It's easier to understand the code and catch bugs when a code base uses common idioms consistently. Idioms are important when you work on a team. Idioms aid consistency and reduce the friction when reading each others code.

Mocky
+1 for mentioning the idiom: fortran developers are used to it. Haskell programmers use `a:as`, Ruby guys use `array.each {|e|...}`
xtofl
I find the assertion 'that it leads to instant readability' highly questionable. It depends. It may well be the case that *what* the index variable is indexing over is useful information. In that case, I would argue, a descriptive name will be more useful both to you *and* to other readers of the code. I was tempted to mark your answer down because its such a blanket statement (but resisted). I'd add that these practices should be looked at as *guidelines*, not *rules*. The difference being the need to think about what you're doing - guidelines being only *generally* appropriate.
Phil
@Phil I think recognizability is more accurate than readability. Editing the answer to reflect that. As an example, if the loop body contains an assignment to "month" it might not seem out of place at first sight but if there is an assignment to i it's immediately obvious as a potential source of trouble.
Mocky
+12  A: 
  1. Developers should not be finding out what the coding standards are for a project during a code review. There should be documentation of the project's coding standards, preferably before coding starts. Often there are multiple approaches to a situation like this (index naming conventions). With established standards, everybody will do it the same way.
  2. Personally, I use a mixed approach. For short blocks, I use i, j, k which everyone will recognize as indexers. For longer blocks with multiple indexes, I give the indexes more meaningful names. It's easy to get lost when reading through nested loops and you can't remember what k is.
DOK
This, exactly. Both 1 and 2.
CPerkins
A: 

Variables with large scope should have long names, variables with small scope can have short names. Scratch variables used for temporary storage or indices are best kept short. A programmer reading such variables should be able to assume that its value is not used outside a few lines of code. So, it all depends on the context and scope of your variables.

Again for better readability, your variable names should be self explanatory unless you are defining loop variables which may have smaller scope.

Dharmesh Sejpal
A: 

I can't recall the time I used i,j,k as an variable name. I always use meaning fullnames. For instance when I just need an indexer to loop throug an array I use index instead of just plain i. By giving it that name I immediately recognize what the variable will be used for. Another example, when you are in need of two indexer (the so called i, j), this is only in the case when you gave nested loops. Again I will try to give it a meaningfull name, mostly row and column. Whenever I would be in need of three loops with indexer, I'm considering redesigning my code.

BadKarmaZen
+3  A: 

I agree with you that month is more useful and descriptive. I can also see the argument that i, j and k are idiomatic, but C idioms aren't always well thought out. That its the thing you're iterating over in the for loop isn't really as important as what's in it. If the loop is small (as it should be), the declaration is right there for all to see.

I certainly wouldn't fail a change for using either style, at least not in C. Its too thin a hair to split. I don't think anyone would really be confused.

In a language that uses iterators it becomes obvious which style is correct.

# Perl
for my $month (@months) {
    ...
}
Schwern
+5  A: 
Jason Williams
What do you call an index variable for pods?
MiseryIndex
A: 

I would say the loop idiom is so well known, that I would vote on using short variable names to avoid clutter; the exception perhaps being where there is a complicated enough nesting to warrant more meaningful names, somewhere in the logic inside the loops....

monojohnny
A: 

It is not a compulsion to use meaningful names for loop construct variables. But, it is surely a good practice. The reason is that sometimes, you will code a particular application and after some time (here, by "some time" I mean days, weeks, months or even years) you might want to check the code for any reason. At such times, you'll not have to wonder what each loop construct variable was purported or intended to do.

Also, during code reviews, the people reviewing the code come to know what a particular code snippet does.

Yash
A: 

I agree with BadKarmaZen, I can not remember the last time I used 'i' as an itterator. I used to think I wrote pretty understandable code and liked the ideom of a single character that specified: indexer. Then I read 'code complete'...

The whole book "Code Complete" (just like 'Design patterns' from the G.o.F.) is about managing complexity. I took a good look at the code I had written thusfar and came to the conclusion that what seems completly obvious at the moment of writing, after 6 months any loop with 'just an indexer' needs to be reverse enginered. (Boy, did my code suck.)

The most important thing that stuck after reading the book has now become my personal mantra: "Things always get more complex/ change is the only constant."

With that in mind, a loop with just an 'i' indexer will grow to the point that the variable name is no longer appropriate and needs to be changed. If you know that in advance you might as well give it a good name to start with. For that very same reason I will always use block delimiters for 'if' statements and throw exceptions in the 'default' clause of an switch statement. If you do not, somewhere in the future it will come back to haunt you.

Of course, using an "for each" loop is even better but not always possible.

Small note: three nested loops with variable names i,j,k is just begging for trouble. Create 100 of those in an application and you'll have a job for life.