StyleFile: Layout

General advice

Layout is, perhaps, the most controversial of the issues of coding style. To debate the pros and cons would make this web page too long; see [Horstmann, 2003] and [McConnell, 1993] to see some of the issues discussed more fully.

Instead, in this web page, I will simply tell you how I want your programs laid out!

In general, you want a layout style that accurately and consistently reflects the logical structure of the program, is readable and withstands modifications (i.e. changing one line of code shouldn't have knock-on effects for the layout of other lines of code) [McConnell, 1993], pp.407-408. I believe that my suggestions below achieve these aims.

Alignment and indentation

Consider a for loop. The layout used by many C programmers, Java programmers and Java textbooks would be:

for (...) {
   statement;
       ...
   statement;
}

Don't use this! For various reasons, the above style works very well in the Ada programming language, but I find it obscures program structure in languages that use curly braces for 'begin' and 'end'.

Instead, I strongly recommend an alternative in which 'begin's and 'end's (curly braces) are aligned (from [Horstmann, 2003]):

for (...)
{  statement;
       ...
   statement;
}

The braces are aligned with each other and with the for command; and the statements in the body are aligned. The first statement is on the same line as the opening brace; the closing brace is on a line on its own. This strikes a balance: there is neither too much indentation, nor too many blank or near-empty lines.

Note that I indent three spaces at each level (but this means that where a line contains both an opening brace and a statement, there are two spaces between the brace and the start of the statement).

Similarly, here's an if statement:

if (...)
{  statement;
      ...
   statement;
}
else if (...)
{  statement;
      ...
   statement;
}
else
{  statement;
      ...
   statement;
}

One further point on the subject of curly braces. Use them even when they are not strictly necessary. Suppose you are writing a for loop that has only a single statement as the body of the loop. You know that, under these circumstances, you are allowed to write the following:

for (...)
   statement;

However, I strongly recommend that you enclose the loop body between braces, even though this isn't strictly necessary:

for (...)
{  statement;
}

Why? Firstly, it spaces your program out a little bit more: what used to take only two lines now takes three but the third is nearly empty, and this breaks the program up on the page in a helpful way. Secondly, and much more importantly, it makes your program much easier to modify. If you ever need to put more statements into the body of the loop, it is ready to receive them from the outset.

Obviously, this advice applies not just to for loops but to all the control structures that are followed by either single statements or brace-enclosed blocks of statements (if, else, while, do, switch and case).

The advice I have given so far is the most significant advice about braces and indentation. The remainder of this section is less important.

Suppose you have a sequence of assignment statements. Should you align the assignment symbols? I.e. should we aim for this:

title    = theTitle;
forename = theForename;
surname  = theSurname;

While pretty, I don't regard this as necessary. It is a convention that makes code harder to maintain: adding another assignment to this sequence may require us to re-align all assignment symbols.

Finally, put only one statement per line. Included in this advice are variable declarations. For example, do not write:

int x, y;

Instead, write:

int x;
int y;

Again it is more straightforwardly modifiable (you simply insert or delete whole lines). And, it makes it easier for you to explain the purpose of each variable in a comment:

int x; // the x coordinate of the centre of the circle
int y; // the y coordinate of the centre of the circle

Whitespace

Spaces for indentation are discussed above.

Also use spaces around operators, and after semi-colons and commas. E.g. compare

for(int i=0;i<s.length();i++)

with

for (int i = 0; i < s.length(); i++)

Some programmers also add spaces after opening and before closing parentheses:

for ( int i = 0; i < s.length(); i++ )

I'm not too worried about this.

You also need to break your whole class definition up with suitable use of blank lines. My advice is that you need a single blank line between each method and constructor.

Within long method and constructor bodies, and within lists of instance variable or class variable declarations, a blank line can be used to separate related groups of statements (much as a document in English is broken up into paragraphs of related text).

Long statements & complex expressions

A statement that is too long for the printed page/your screen will have to be split over several lines. Try to break the line so that it ends with a symbol that makes it clear that the statement isn't complete, e.g. an operator. Indent the next line by three. For example:

System.out.println("This is a long string but note how I leave a " +
   "plus sign at the end of the previous line rather than at the " +
   "beginning of the next line so that the reader can more easily " +
   "see that the line isn't complete.");

Complex expressions should be broken over several lines and indented in a way that reveals their structure:

while (((a == 1) && (b == 2)) ||
       (c == 3))
{  statements;
}

(Actually, gruesome boolean expressions or other gruesome expressions are often better placed into a separate method of their own.)

Ordering the parts of a class definition

Your programs will be more easily read if the order of items within class definitions follows some convention. My own convention (based on one in [Gilbert & McCarty, 1998]) is to base every class definition on a template that places constructors first, public constants second, public getters third, and so on. It uses some simple comment lines to divide up the file to make it easier to find things when scanning through the file.

Here is the template:

package <package name>;

import <package>;

/**
 * <Class description>
 * @author <author name>
 */
public class <class name>
   extends <superclass>
   implements <interfaces>
{
/* =======================================================================
       CONSTRUCTORS
   =======================================================================
*/

/* =======================================================================
       PUBLIC INTERFACE
   =======================================================================
*/

/* --Public class constants-------------------------------------------- */

/* --Getters----------------------------------------------------------- */

/* --Setters----------------------------------------------------------- */

/* =======================================================================
       HELPER METHODS
   =======================================================================
*/

/* =======================================================================
       INSTANCE VARIABLES & CLASS VARIABLES
   =======================================================================
*/

/* =======================================================================
       TEST DRIVER
   =======================================================================
*/
   public static void main(String[] args)
   {
   }
}