Java Language Coding Guidelines

Introduction

A style guide is a set of mandatory requirements for layout and formatting. Students are expected to follow this style guide when submitting programs in Dr. East's section of 810:061 Computer Science I. The goal here is to supply a subset of coding style useful for an introductory course in Java. This document is an adaptation of that supplied by Cay Horstmann with his text Big Java (available at http://www.horstmann.com/bigj/style.html). Horstmann's guide contains rationale and discusstion not included here.

Source Files

Each Java program is a collection of one or more source files. The executable program is obtained by compiling these files. Organize the material in each file as follows:

The comment explaining the purpose of this file should be in the format recognized by the javadoc utility. Start with a /**, and use the @author and @version tags:

/**
    Classes to manipulate widgets.
    Solves CS101 homework assignment #3
    COPYRIGHT (C) 1997 Harry Hacker. All Rights Reserved.

    @author Harry Hacker
    @version 1.01 1997-02-15
*/

Classes

Each class should be preceded by a class comment explaining the purpose of the class.

First list all public features, then all private features.

Within the public and private section, use the following order:

  1. Constructors
  2. Instance Methods
  3. Static Methods
  4. Instance Fields
  5. Static Fields
  6. Inner classes

Leave three blank lines after every method (or begin them on a new page, if you control paging).

All non-final variables must be private. (However, instance variables of a private inner class may be public.) Methods and final variables can be either public or private, as appropriate.

All features must be tagged public or private.

Avoid static variables (except final ones).

Methods

Every method (except for main) starts with a comment in javadoc format. Include citations/references and include any expecatations of the method.

/**
    Convert calendar date into Julian day.
    Note: This algorithm is from Press et al., Numerical Recipes in C, 
          2nd ed., Cambridge University Press, 1992
    Note: Expects day, month, and year to represent a date after 
          Jan. 1, 1601.

    @param day day of the date to be converted
    @param month month of the date to be converted
    @param year year of the date to be converted

    @return the Julian day number that begins at noon of given calendar date.
*/
public static int dat2jul(int day, int month, int year)
{ 
    . . .
}

Methods must have at most 30 lines of code. The method signature, comments, blank lines, and lines containing only braces are not included in this count.

In-code Documentation

Avoid comments that duplicate code, e.g.,

int  vowelCount;  // count of vowels

for (int i=1;  i <= 100;  i++ )  // count to 100
    {}

Make comments distinguishable from code, e.g.,

                           // determine location of minimum value
int  least = 0;
for (int i=1;  i <= value.length();  i++)
{
    if  (value[i] < value[least])
        { least = i; }
}
instead of
// determine location of minimum value
int  least = 0;
for (int i=1;  i <= value.length();  i++)
{
    if  (value[i] < value[least])
        { least = i; }
}

Variables and Constants

Do not define all variables at the beginning of a block. Instead, define each variable just before it is used for the first time:

{ 
    . . .
    double xold = Integer.parseInt(input);
    boolean more = false;
    while (more)
    {  
        double xnew = (xold + a / xold) / 2; // OK
        . . .
    }
    . . .
}

Do not define two variables on the same line:

In Java, constants must be defined with the keyword final. If the constant is used by multiple methods, declare it as static final. Define static final variables as private.

Do not use magic numbers! A magic number is a numeric constant embedded in code, without a constant definition. Any number except -1, 0, 1, and 2 is considered magic:

When declaring array variables, group the [] with the type, not the variable.

int[] values; // OK
int values[]; // Ugh--this is an ugly holdover from C

Control Flow

The if Statement

Avoid the "if ... if ... else" trap. The code

if ( ... )
    if ( ... ) ...;
else ...;
will not do what the indentation level suggests, and it can take hours to find such a bug. Always use an extra pair of { ... } when dealing with "if ... if ... else":

if ( ... )
{  
    if ( ... ) ...;
} // {...} are necessary
else ...;

if ( ... )
{  
    if ( ... ) ...;
    else ...;
} // {...} not necessary, but they keep you out of trouble

The for Statement

Use for loops only when a variable runs from somewhere to somewhere with some constant increment/decrement. Do not use the for loop for weird constructs such as:

for (a = a / 2; count < ITERATIONS; System.out.println(xnew))
    // Don't
Make such a loop into a while loop. That way, the sequence of instructions is much clearer.

Nonlinear Control Flow

Avoid the switch statement, because it is easy to fall through accidentally to an unwanted case. Use if/else instead.

Avoid the break or continue statements. Use another boolean variable to control the execution flow.

Exceptions

Do not tag a method with an overly general exception specification:

Widget readWidget(Reader in)
    throws Exception // Bad
Instead, specifically declare any checked exceptions that your method may throw:

Widget readWidget(Reader in)
    throws IOException, MalformedWidgetException // Good

Do not "squelch" exceptions:

try
{ 
    double price = in.readDouble();
}
catch (Exception e)
{} // Bad

Lexical Issues

Naming Convention

The following rules specify when to use upper- and lowercase letters in identifier names.

Make names reasonably long & descriptive. Use firstPlayer instead of fp. No drppng f vwls. Local variables that are fairly routine can be short (ch, i) as long as they are really just boring holders for an input character, a loop counter, and so on. Also, do not use crt, n, pv, vCnt, for variables in your method. Surely these variables all have specific purposes and can be named to remind the reader of them (for example, current, next, previous, vowelCount, . . . ).

Indentation

Use tab stops every three or four columns.

Indent each statement within the scope of a statement by one level:

if ( . . . )
{
    int  location = 0;
    while (location <= value.length() 
            && value[location] <= target)
    {
        location++;
    }
}

Every line must fit on 78 columns. If you must break a statement, add an indentation level (or two) for the continuation. Start the indented line with an operator (if possible).

a[n] = ..................................................
    + .................;

If the condition in an if or while statement must be broken, be sure to brace the body in, even if it consists of only one statement:

if ( .........................................................
    && ..................
    || .......... )
{  
    . . .
}

Avoid single- or in-line statements, e.g.,

if (x == 0)  y = 0;

for (int i = 0; i < a.length; i++)  System.out.println(a[i]);

White Space

Use blank lines freely to separate parts of a method that are logically distinct.

Use more blank lines between code segments than are used within them.

Use a blank space around every binary operator and around sets of parentheses or brackets that form expressions but not between them:

x1 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);        // Good
x1 = ( -b  -  Math.sqrt(b * b - 4 * a * c) )  /  (2 * a);  // Also okay

x1=(-b-Math.sqrt(b*b-4*a*c))/(2*a);  //Bad

Leave a blank space after (and not before) each comma or semicolon.

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++;
}

Unstable Layout

Some programmers take great pride in lining up certain columns in their code. This is undeniably neat, but the layout is not stable under change. Avoid doing it.

firstRecord = other.firstRecord;
lastRecord  = other.lastRecord;
cutoff      = other.cutoff;

Do not use // comments for comments that extend for more than two lines. You don't want to have to move the // around when you edit the comment.

// comment — don't do this
// more comment
// more comment

Use /* ... */ comments instead. When using /* ... */ comments, don't "beautify" them with additional asterisks:

/* comment—don't do this
 * more comment
 * more comment
 */

Instead, format long comments like this:

/*
   comment
   more comment
   more comment
*/

These comments are easier to maintain as your program changes. If you have to choose between pretty but unmaintained comments and ugly comments that are up to date, truth wins over beauty.




Comments and suggestions welcomed (via e-mail).
My students can receive a little extra credit for good (grammar or content) suggestions.