Adept Software Development

Adept: (A)pplication (D)evelopment (E)nterprise to (P)ersonal (T)ransition. It is a system I am developing to leverage Enterprise developer skills to produce stand-alone software for other market segments. This is a general software development blog discussing issues about project, architecture, design and development. The emphasis will be in Java, but many of the issues will be more general. Almost all will be technical.

http://marringtons.com

Wednesday, January 19, 2005

For now or While away?

The venerable for(;;) loop construct was invented for C in the 70's and has survived unchanged through C++ to Java. It was originally designed to be more flexible than the counter loop constructs for earlier languages such as BASIC or FORTRAN, which typically only allowed integer counters between a range with an optional step.
FOR i between 1 and 20 step 3

 

was the same as
for (i = 1; i < 20; i += 3)

 

Where the for(;;) loop shines is in other boolean loops.

But consider:

for (o = first(); o != null; o = next())

 

Here we are rapidly losing readability. In truth the for(;;) loop was never very logical. Generations of IT teachers have had to explain that part one occurs above the loop, part two as the first statement of the loop and part 3 at the end. In an industry where logic rules, we have to take the for(;;)loop on faith. The above loop is easier and quicker to read as:

MyObject o = first();
while (o != null)
  {
    ...
    o = next();
  }

 

By all means use for(;;)for simple iterations, but as soon as the logic becomes complicated, consider changing it to a while() loop.

0 Comments:

Post a Comment

<< Home