I'm just sayin'...

And I quote...

Java Language Coding Guidelines

This coding style guide is a simplified version of one that has been used with good success both in industrial practice and for college courses.

A1.7.3—Braces

Opening and closing braces must line up, either horizontally or vertically:

    while (i < n) { System.out.println(a[i]); i++; }
    while (i < n)
    {
        System.out.println(a[i]);
        i++;
    }
Some programmers don't line up vertical braces but place the { behind the key word:
    while (i < n) { // DON'T
        System.out.println(a[i]);
        i++;
    }

Braces should always be used within blocks of code, even if one or no lines of code are contained within that block (e.g. within if, else, for, while, do...while, catch, finally, etc.). Also, braces should always appear on their own line. This applies to both opening and closing braces, in all usages. For example:

    if (bDoIt)
    {
        // Do some stuff...
    }
    else
    {
        // Don't do anything...
    }

This approach comes at the expense of vertical space, however it visually groups blocks of related code, making it clear and obvious to the programmer where the boundaries of that block of code are. This can be obscured if the opening clause spans multiple lines, or if the location of the opening brace is not visually. For example, consider the following comparison:

    if (bAlive && someObject.checkTheString(sName.substring(start, end) && 
        anotherObject.testThisThing(thing)) {
        anotherObject.process(thing);
    }

versus:

    if (bAlive && someObject.checkTheString(sName.substring(start, end) && 
        anotherObject.testThisThing(thing))
    {
        anotherObject.process(thing);
    }

In the first example, it is less clear at a glance whether the call to process is within the if or not. It requires the programmer to scan each line following the if to find the curly brace. In contrast, in the second example the programmer does not need to look beyond the first column to know where the if block begins.

I can find plenty of examples which contradict this usage and place the opening brace at the end of the line. However I can't find any reasoning for doing so as indicated above. Considering the symetry and logic of the style suggested above, I highly recommend this methodology over the latter.

2/9/2008 | Comments (0) in Java
Email