As I see it the potential danger of using a variable is; if within the loop, the loop counter
may change its value. It probably doesn't in this case, but I suspect the example was given as that, an example.
Changing the example as follows:
Code:
int listSize = ledger.length;
for (int i=0;i<listSize;i++)
{
ledger.balance(i);
}
// Where balance() is defined as:
balance(int)
{
if (endOfMonth)
{
addEOMDirectDebits();
}
total += getSubTotal();
}
// And addEOMDirectDebits() is defined as:
addEOMDirectDebits()
for (int i=0; i<ledger.myAccount().getEOMDDList().length(); i++)
{
addDDtoLedger(i);
}
// The addDDtoLedger() method will now modify the size of the ledger and thus ledger.length
Sorry for the long example, but I believe that it demonstrated what I am getting at. Stepping through this code we see that if this is being run at the end of the month then the variable used in the original condition ledger.length can change, and even then it will only change if we have direct debits due at the end of the month.
Now consider this, you wrote the code before any banking wizard thought of direct debits as a means of reducing their administratve costs. They didn't exist. You substituted ledger.length with a variable for optimisation reasons.
Now direct debits have been introduced and the code needs to be modified, it is given to newbie coder to implement,(whilst I agree there may be issues with how I've implemented it here, I am after all a newbie coder)
I test my code, it works the items are added to the ledger, sign the code off and time to celebrate, job well done.
Unfortunately because the code all runs and a total is calculated from the original loop it will probably be accepted for several months before someone realises that not all the ledger entries are being totaled up.
Consider the second loop, it has the condition of
Code:
ledger.myAccount().getEOMDDList().length()
I would suggest that this could be optimised in the following way:
Code:
EOMDDList eomDDList = ledger.myAccount().getEOMDDList()
for (int i=0; i<eomDDList.length(); i++)
{
addDDtoLedger(i);
}
It still has a method call in the loop but is able to remove two method calls and return the end of month Direct Debit List object. That isn't 100% safe but if the object changes within the loop then that is really bad coding, however when newbie coder does come along to implement the addEOYDirectDebit method inside the addDDtoLedger() method within an if endOfYear() condition then it
shouldn't break the code.
Anyway I hope that helps, and for what it is worth; when you can leave the optimisation to the compiler
cheers,
graeme.