Naming Iterators
During a recent peer code review, a for loop caught my eye. It caught my eye because it dawned on me that despite having used variable naming conventions for years, just about every for loop I had used defied the naming convention, and no-one was batting an eyelid.
I'm talking about the iterator i, of course. Effectively a local variable, with a meaningless name and according to my convention, starting with the wrong case.
But i is traditional in a for loop, isn't it? It's kind of comforting. As programmers, we just know that i is an iterator. Along with, sometimes, j. But how far should we let this go? Are j and k acceptable?
I think you might make a case for j, if it's really clear what the iterator relates to. Beyond that, things can quickly become confusing.
So here's the new rule we came up with for iterator naming convention:
If there's just one iterator, you can use i, but if there's more than one nested iterator, give the iterator a meaningful name.
I still love i, and now we can still be together!
for (int i = 0; i < WordArray.Length; i++ )
{
WordArray[i] = WordArray[i].Trim();
}
I'm talking about the iterator i, of course. Effectively a local variable, with a meaningless name and according to my convention, starting with the wrong case.
But i is traditional in a for loop, isn't it? It's kind of comforting. As programmers, we just know that i is an iterator. Along with, sometimes, j. But how far should we let this go? Are j and k acceptable?
I think you might make a case for j, if it's really clear what the iterator relates to. Beyond that, things can quickly become confusing.
So here's the new rule we came up with for iterator naming convention:
If there's just one iterator, you can use i, but if there's more than one nested iterator, give the iterator a meaningful name.
I still love i, and now we can still be together!
Labels: Randoms
0 Comments:
Post a Comment
<< Home