Java Coding Standard for CS 111 & CS 108

| Naming | Curly Braces | Indentation and Whitespace | Comments | Miscellaneous |

This document contains a summary of the most important recommendations Java Coding Standards, mostly concerned with layout of code and comments, and with the choice of good names. These have been derived by my own experience and a brief survey of online resources, the most important of which are listed on the Java and Eclipse Links page.

These recommendations are consistent with almost all Java style recommendations in the literature, and are followed by almost all Java programmers. You should use them unless you are specifically required to to do otherwise by a future employer or instructor. They are designed to improve code readability, on the premises that far more human time is spent reading code than writing it, that far more human time is spent modifying existing code than writing entire programs from scratch, that far more code is written by groups of people than by single individuals. In particular, following these rules will make it easier for the grader to grade your work and the instructors to assist you if you are having difficulty. They will also help you think more clearly about your code!

When there is a difference between what is done in the textbook and what is outlined here, this takes precedence.


Naming

Choose your names carefully. As part of program documentation, names must clearly indicate both the kind of thing being named and its role in the program. Whenever possible, write short, obvious names for very local contexts (i.e., a for loop counter could be called i) and longer names for bigger contexts (examples to follow). Avoid cryptic abbreviations (e.g.,use incrementEventCount() rather than incEvCnt()). Avoid choosing similar names for different things, e.g., index, indx, index2; or, on the other hand, similar names for very different things (example: if keys[] is a array of strings, then don't use key for an integer for loop counter).


Curly Braces

Curly braces delimit the bodies of classes, methods, and loops. There are two standard formats for braces:

1. Curly brace goes at the end of the line that starts the class, method, loop, etc., and the closing brace is on a line by itself, lined up vertically with the start of the first line (this is the default format in Eclipse)

class SomeClass{
    ... 
    public SomeClass(){ // Constructor
    ... 
    } 
    int someMethod(int n,float m){
        ... 
        for(int i=0;i<someField;++i) {
            ....
        }
    return ...;
    }
}   

2. Each curly brace is on a new line, and a pair is lined up vertically. This is the required format for this class. The previous code in this format would look like this:

class SomeClass
{
    ... 
    public SomeClass()
    { // Constructor
        ... 
    } 
    int someMethod(int n,float m)
    {
        ... 
        for(int i=0;i<someField;++i) 
        {
            ....
        }
        return ...;
    }
}

You can reset the default in Eclipse to generate this format by default. To do this, in Eclipse follow Window -> Preferences -> Java -> CodeStyle -> Formatter. Now in the window at the right, edit a new profile: click the New button, name your profile (e.g. cs111) and then edit the profile. Activate the Braces tab and there change the brace position to 'New line' for the class, anonymous class, methods and constructor declaration and the same for 'blocks', 'blocks in case statement' and  'switch'.


Indentation and Whitespace

The placement of syntax on the page is one of the most important aspects of style and readability, and has three aspects: horizontal placement is achieved by (i) using spaces or tab stops to indent lines of code and other similar items (such as variables in a series of declarations), (ii) for inserting "oxygen" around operators and punctuation, and vertical placement is achieved by (iii) inserting blank lines to separate classes, members of classes, and regions of code with various purposes.

The usual standard for indentation is to

This is the most obvious effect of the Eclipse indent command (Control-I). Example:

class SomeClass
{
    int someField; 

    double anotherField; 
    public SomeClass()
    { // Constructor
        someField=1;

        anotherField = 3.14; // Initialize all fields
    } 
    int someMethod(int n,float m)
    {
        int localVariable=0; // Must initialize local variables
        float anotherLocalVariable=1; // This one too
        localVariable=n-2;
        anotherLocalVariable=localVariable+m*3; 
        for(int i=0;i<someField;++i) 
        {
            localVariable=localVariable*2;
            localVariable=localVariable-someField;
        }
        return localVariable+n;
    }
}
   

This example is not in fact very readable, as it it hard to parse the structure of the individual lines; the usual standard for increasing readability of each line is:

Superfluous parentheses can also help to emphasize the structure of expressions (but not too many nested parentheses). This example, should thus be written as:

class SomeClass 
{
    int someField; 

    double anotherField; 
    public SomeClass() 
    {                                      // Constructor
        someField = 1; 
        another Field = 3.14;              // Some people line up a series of initializations too. 
    } 
    int someMethod(int n, float m) 
    {
        int localVariable = 0;             // Must initialize local variables
        float anotherLocalVariable = 1;    // This one too
        localVariable = (n - 2);
        anotherLocalVariable = localVariable + (m * 3); 
        for (int i = 0; i < someField; ++i) 
        {
            localVariable = localVariable * 2;
            localVariable = localVariable - someField;
        }
        return (localVariable + n);
    }
}

Still too crowded! For vertical arrangement, simply

class SomeClass
{
    int someField;
    double anotherField;

    public SomeClass()
    {                                       // Constructor
        someField = 1;
        anotherField = 3.14;                // Initialize all fields
    }

    int someMethod(int n, float m)
    {
        int localVariable = 0;              // Must initialize local variables
        float anotherLocalVariable = 1;     // This one too

        localVariable = n - 2;
        anotherLocalVariable = localVariable + m * 3;

        for (int i = 0; i < someField; ++i)
        {
            localVariable = localVariable * 2;
            localVariable = localVariable - someField;
        }

        return localVariable + n;
    }
}

Three or four blank lines should be used to separate class and interface definitions, when they occur in the same file.


Comments

Comments should help the reader of your code to understand it. They may help YOU to understand it if you need to rework your code at some later point. In the case of a programming course, they also serve to convince the grader that you grasp the what, how and why of your code (as opposed to having hacked it into working). Like any other form of expression, it should not be flowery or repetitive. In particular observe the following guidelines.

Miscellaneous

Keep Line Lengths Under 80 characters

On many machines and in many software packages, this is a standard line length. It makes it easier for others (like graders) to read and/or print your programs. If your parameter list for a method is too long to fit within 80 characters, then insert line breaks and use indentation to line up the parameters:

boolean calculateAverageDailyReturn(int customerID, double dailyBalanceForMonth[], double dailyInterestRate, double discountRate) 
{
should be rewritten as:
boolean calculateAverageDailyReturn(int    customerID, 
                                    double dailyBalanceForMonth[], 
				    double dailyInterestRate, 
				    double discountRate) 
{
If your println statement is too long, then you should break this up as well, using the + operator to concatenate strings:
System.out.println("The average daily return for customer " + customerID + " at the discount rate " + discountRate + " is " + A);
should be rewritten as:
System.out.print("The average daily return for customer " + customerID +
               + " at the discount rate " + discountRate + " is " + A);


Written by: Wayne Snyder (Fall 2004)
Updated: Alexandra Stefan (Spring 2006)
Updated: Aaron Stevens (Summer 2008)