Use the same looping techniques as everyone else.

Most loops follow the same basic pattern, starting at zero and counting up by one to the maximum value.  Resist the desire to start at numbers other than zero (e.g. i=1) or to count in reverse (e.g. i--) unless a clear reason to do so exists.  Follow the recommended pattern where possible, as in the following example:

for (int i=0; i<itemCount; i++)
{
    :
}

To illustrate how confusing the loop can be written, the following example starts at 1 and sets i to 101 to exit the loop.  Most developers would find this difficult to follow, especially when further investigation shows there is no special reason why the loop starts at 1 instead of 0.

for (int i=1; i<=100; i++)
{
    // processing
    :
    if (resultsFound) i = 101;  // quits the loop
}

The traditional way to write the code would be to start at 0 and use break to exit the loop as below:

for (int i=0; i<100; i++)
{
    // processing
    :
    if (resultsFound)
    {
        break;  // quits the loop
    }
}

Unless there is some reason you are stuck with an older version of the Java Virtual machine, the loops written using Java 1.5 Syntax is like going on a mini-holiday:

for (Document document: documents)
{
     :
 }

Tip: most language features are approached in a common way by the majority of developers so try and fit in.  Don't invent your own way without a good reason.  Most workplaces will expect you to find alignment with your peers.

blog comments powered by Disqus