Is it better to use the variable 'i' or a meaningful name such as 'loopCount' or 'studentsCount' etc?
e.g.
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 5; j++)
{
System.out.println(i + j);
} // End of j loop
} // End of i loop
VS
for (int outerLoop = 0; outerLoop < 10; outerLoop++)
{
for (int innerLoop = 0; innerLoop < 5; innerLoop++)
{
System.out.println(outerLoop + innerLoop);
} // End of innerLoop
} // End of outerLoop
By better; the main considerations would be readability / conventions.
Related question Loop iterator naming convention
EDIT: I have tagged this a java, but answers for other languages are welcome.
Firstly, using Integer here is very expensive because Integer is immutable. Thus each time you do an increment it unboxes the previous Integer, do an increment and creates another Integer to hold the new value. You need to use int.
Secondly, whether to have a readable name really up to the semantics of the int. If it's just a control variable over a pre-determined number of loops I think i is fine; but if it has specific meaning then you are free to give it a better meaningful name.
Code is communication: what do you want the reader of this code (who might be you months or years from now) to think when he sees it? To me, using "i" and "j" in a loop says "do this thing 10 times; the variable is just a convention and means nothing", while using a more descriptive variable like "studentID" says "this number actually refers to something specific" I'd use the former if I want to de-emphasize the variable itself, and the latter if I want to highlight it.
I have seen many loops that started out small and grew very large with other loops added inside and around them and it all became a confusing mess of i j k x y z. Name your references with the shortest name that expresses your intent, so another dev will know what you were going for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With