Paul Haahr / Essays / Java Style / Idioms

Idioms

All languages support constructs which might not be clear to a beginning user, but are frequently employed by experienced users. Some languages (including C, APL, and Lisp) often seem to encourage the development of idioms which are hard to follow.

The idioms I discuss here are typical of my usage of Java. None is, I hope, hard to follow, but all may seem somewhat odd to a programmer coming from another language, notably C.

Use ``while (true)'' for infinite loops

I've seen the C-preprocessor definition:

 #define ever (;;)
used in strange, failed attempts to make this syntax clearer.

Many C programmers (yours truly sometimes included) use the construct ``for (;;)'' for infinite loops. My reasoning was that I couldn't count on ``true'' being defined in all C programs, and ``while (1)'' looks strange to my eyes.

Java has a boolean type, so even that specious argument doesn't hold water -- the right thing to use is simply ``while (true)''.

Set loop limits in for-initialization clauses

The initialization clause of a for statement is executed exactly once, where the termination test is executed every time around the loop. If the upper bound on a numeric (typically integer) loop could be changed by execution of the loop and one does not want to use the changed value (or if the upper bound is time-consuming to compute) the loop limit can be declared and set along with the iteration variable in the initialization clause. By using this form, neither variable's scope extends outside the loop.

For example, this is a typical loop from the compiler for visiting every node in the graph representing a program:

    for (int i = 0, n = flowgraph.getNodeCount(); i < n; i++) {
        Node node = flowgraph.getNode(i);
        if (node != null)
            visitNode(node);
    }

Roughly one-third of the integer for loops in our compiler take this form. Some usages probably fall into the category of premature optimization, but when I look an integer for loop with a complex termination expression, I end up wondering whether it was intentional or not to re-evaluate the termination, and coding in this style answers that question implicitly.


Back: Errors and Exceptions
Next: Other Style Guides