Re: Improved for each loop
On Tue, 14 Jul 2009 12:42:30 -0700, Tom Anderson <twic@urchin.earth.li>
wrote:
[...]
Iterator<String> it = someCollectionOfStrings.iterator();
while (it.hasNext()) {
s = it.next()) {
fooBarDoStuff();
if (it.hasNext()) doSomethingOnlyForTheLastElement();
}
I feel your pain. That said, "last element only" logic should be avoided
where possible anyway; I know it does come up, but any exceptional logic
in your code is just another chance for a maintenance error. As a rare
occurrence, it's not really the sort of thing that should drive a language
feature.
Also, when you must have that kind of thing, note that it's not strictly
necessary to access the iterator directly (which is verbose, painful, and
potentially error-prone). Instead, you could do something like this:
String strPrev = null;
for (String strCur : someCollectionOfStrings)
{
fooBarDoStuff(strCur);
strPrev = strCur;
}
if (strPrev != null)
{
doSomethingOnlyForTheLastElement(strPrev);
}
And other variations on that theme. IMHO, one advantage is that it takes
the exceptional logic out of the loop completely, which is a maintenance
benefit. After all, that exceptional thing really has little to do with
the loop itself; that is, it's not actually a repeated action, so having
the code in a loop (which is inherently about repeating actions) is
misleading, while having it outside the loop is more suggestive to the
reader of the true purpose.
It's not quite as concise as being able to just check the status of your
iterator inside the loop (the only real difference being the "if"
statement after the loop); but IMHO what marginal increase in code size
results is actually a benefit, rather than a flaw.
Pete