Loop antipattern

Consider the following snippet:

boolean left = true;
int m = 0;
while (m < 2400) {
  System.out.println(left ? "left" : "right");
  left = !left;
  m++;
}

could be improved as:

for (int m=0;m<2400;m++) {
  System.out.println(m%2==0 ? "left" : "right");
}

The antipattern to be recognized here are:

  1. The number of iterations was known at compile-time. This is a hint to use for loops. Whiles are used when the number of iterations are unknown. Although it is possible to write it as a while loop, a for loop makes your intention concise, and less error-prone (such as forgetting to increment).
  2. Modulus can be used for “cycles”. In this case it was a 2-item cycle, therefore a ternary operator was used. A cycle with more items can also be used by using an array to reference the items, then use array[m%array.length] to index the cycle item.

Disclaimer: Although the code was actually written (not by me), it is not meant to shame or blame. It is to be taken as a lesson for sharing and improvement.

1 Comment »

  1. phishie said,

    January 27, 2008 at 11:57 pm

    The code was written in MSN comment; maxed out.

RSS feed for comments on this post · TrackBack URL

Leave a Comment