Saturday, July 26, 2008

Write Easy to Read For Loop



When it comes to for loops, first thing a programmer thinks is what to name the counter variable. I am talking about old styled for as shown below :

for (int i=0; i <>
// really long body.
}

What to name the counter variable? If you name just i or j as shown above, it is not readable, but it easy to program. If you name something meaningful e.g. someItemOccurenceCount, it is painful to copy and paste when you need it e.g: someArray[someItemOccurenceCount]. IDE's auto-completion feature is useful, but to invoke every time is a pain.
Well with any IDE, you are in luck. You just write the loop with i, j, or k, or any of your favorite alphabet. Once you have finished writing the whole loop, just use refactoring. And look, IDE will change the one letter counter with any meaningful word you might choose.

No comments: