CS Resources—Java; Appendix A1. Java Language Coding Guidelines

Note: These coding guidelines are a part of the book "Computing Concepts with Java Essentials" by Cay S. Horstmann, published by John Wiley & Sons. They are copyright © 1997, by John Wiley & Sons. All Rights Reserved.

A1.1. Introduction

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. It lays down rules that you must follow for your programming assignments.

A style guide is a set of mandatory requirements for layout and formatting. Uniform style makes it easier for you to read code from your instructor and classmates. You will really appreciate that if you do a team project. It is also easier for your instructor and your grader to quickly grasp the essence of your programs.

A style guide makes you a more productive programmer because it reduces gratuitous choice . If you don't have to make choices about trivial matters, you can spend your energy on the solution of real problems.

In these guidelines, a number of constructs are plainly outlawed. That doesn't mean that programmers using them are evil or incompetent. It does mean that the constructs are of marginal utility and can be expressed just as well or even better with other language constructs.

If you have already programmed in C or C++, you may be initially uncomfortable at giving up some fond habits. However, it is a sign of professionalism to set aside personal preferences in minor matters and to compromise for the benefit of your group.

These guidelines are necessarily somewhat dull. They also mention features that you may not yet have seen in the class. Here are the most important highlights:

  1. Tabs are set every three spaces
  2. Variable and function names are lowercase
  3. Constant names are uppercase
  4. There are spaces after keywords and between binary operators
  5. Braces must line up
  6. No magic numbers may be used
  7. Every function must have a comment
  8. At most 30 lines of code may be used per function
  9. No continue or break is allowed
  10. All data fields must be private

A note to the instructor: Of course, many programmers and organizations have strong feelings about coding style. If this style guide is incompatible with your own preferences or with local custom, please feel free to modify it. For that purpose, this coding style guide is available in electronic form from the author.

A1.2. 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:

Here is a sample copyright notice.

/* COPYRIGHT (C) 1997 Harry Hacker. All Rights Reserved. */

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

   A class to manipulate widgets. 
   Solves CS101 homework assignment #3
   @author Harry Hacker
   @version 1.01 1997/2/15

A1.3. Classes

In every class, first list all public features, then all private features. List features in the following order:

CS132 Note: We often find placing the data fields, constants and static variables first makes the development of the class easier. Consequently, we will often show code where these items are listed first and don't really care whether you give them first or last. But please group all of methods together and all the instance variables and data fields together.

Leave a blank line after every function, and between the public and private section.

All data fields and static variables must be private.

Functions and constants can be public or private, as appropriate.

All features must be tagged public or private. Do not use the default visibility (that is, package visibility) or the protected attribute.

Supply a default constructor for every class.

Avoid static variables whenever possible. In the rare instance that you need static variables, you are permitted one static variable per file.

A1.3. Functions and Methods

Every function (except for main) starts with a comment in javadoc format.

   Convert calendar date into Julian day.
   Note: This algorithm is from Press et al., Numerical Recipes in 
   C, 2nd ed., Cambridge University Press 1992 
   @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 the given 
   calendar date. 
public static int dat2jul(int d, int m, int y) 
{ . . . 

Parameter names must be explicit, especially if they are integers or Boolean.

public Employee remove(int d, double s)
 /* Parameter names are not very descriptive */ 
public Employee remove(int department, double severancePay)
 /* Parameter names are clear and easy to understand */ 

Of course, for very generic functions, short names may be very appropriate.

public static void sort(int[] a)
 /* OK */ 

Functions must have at most 30 lines of code. The function header, comments, blank lines and lines containing only braces are not included in this count. Functions that consist of one long if/else may be longer, provided each branch is 10 lines or less.

This rule forces you to break up complex computations into separate functions.

A1.4. Variables and Constants

Do not define all variables at the beginning of a block.

public static double squareRoot(double a)
{  double xOld; /* Don't */ 
   double xNew;
   boolean more; 
    . . .

Define each variable just before it is used for the first time.

public static double squareRoot(double a)
{  . . .
      double xNew = (xOld + a / xOld) / 2; 
      . . . 
   . . .

Do not define two variables on the same line

int dimes = 0, nickels = 0; /* Don't do this */ 

In Java, constants must be defined as static final values in the class, outside any function. It is a good idea to define them as private if no other class has an interest in them.

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

if (p.getX() < 10) /* Don't do this */ 

Use static final instead.

public static final double WINDOX_XMAX = 10; 
. . .
if (p.getX() < WINDOW_XMAX) /* You can do this */ 

Even the most reasonable cosmic constant is going to change one day. You think there are 365 days per year? Your customers on Mars are going to be pretty unhappy about your silly prejudice. Make a constant

public static final int DAYS_PER_YEAR = 365; 

so that you can easily produce a Martian version without trying to find all the 365's, 364's, 366's, 367's, and so on, in your code.

A1.5. Control flow

A1.5.1. The if statement

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

if( ... ) 
      if( ... ) ...; 
   {  ...; 

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( ... ) ...; 
   else( ... ) ...; 
} /* {...} not necessary but they keep you out of trouble */ 

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

A1.5.2. The for statement

Only use for loops when a variable runs from somewhere to somewhere with some constant increment/decrement.

for (i = 0; i < a.length; i++) 

Do not the for loop for weird constructs such as

for (a = a / 2; count < ITERATIONS; System.out.println(xnew)) 
   . . .
/* Don't do this */ 

Make such a loop into a while loop. That way, the sequence of instructions is much clearer.

a = a / 2; 
while (count < ITERATIONS) /* This is okay to do */ 
{  . . .

A for loop traversing a linked list can be neat and intuitive:

for (a.reset(); a.hasMoreElements(); a.nextElement()) /* Ok */

For usage of braces, it is usually not necessary to use them when the for loop contains only one statement. However, it is advisable to make it a habit to use braces for all for loops.

A1.5.3 The while statement

For usage of braces, it is usually not necessary to use them when the while loop contains only one statement. However, it is advisable to make it a habit to use braces for all while loops.

A1.5.4. Nonlinear control flow

Don't use the switch statement. Use if/else instead.

Do not use the break or continue statements. Use another boolean variable to control the execution flow.

A1.6. Lexical issues

A1.6.1. Naming convention

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

1. All variable and function names and all data fields of classes are in lowercase (maybe with an occasional upperCase in the middle). For example, firstPlayer .

2. All constants are in uppercase (maybe with an occasional UNDER_SCORE). For example, CLOCK_RADIUS .

3. All class names start with uppercase and are followed by lowercase letters (maybe with an occasional UpperCase letter). For example, BankTeller .

Names must be reasonably long and descriptive. Use first_player 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 etc... And, do not use ctr , c , cntr , cnt , c2 for five counter variables in your function. Surely these variables all have a specific purpose and can be named to remind the reader of it (e.g. cCurrent , cNext , cPrevious , cNew , cResult ...).

A1.6.2. Indentation and white space

Use tab stops every 3 columns. That means you will need to change the tab stop setting in your editor!

Use blank lines freely to separate logically separate parts of a function.

Separate functions by comments like /*---------*/ .

Use a blank space around every binary operator.

x1 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a); /* Good */ 

Leave a blank spaces after (and not before) each comma, semicolon, and keyword, but not after a function name.

if (x == 0) 
f(a, b[i]); 

Every line must fit on 80 columns. If you must break a statement, add an indentation level for the continuation:

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

If this happens in an if or while , be sure to brace in the next statement, even if there is only one.

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

If it wasn't for the braces, it would be hard to visually separate the continuation of the condition from the statement to be executed.

A1.6.3. Braces

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

while (i < n) { print(a[i]); i++; } 

while (i < n) 
{  print(a[i]); 

Some programmers don't line up vertical braces but place the { behind the while.

while (i < n) {            /* Don't do this */ 

But that makes it hard to check that the braces match. Other programmers place the { in a line all by itself. That isn't a good idea because it wastes a line of precious screen space.

while (i < n) 
{                             /* Don't do this */ 

The trick is not to leave a blank line after the opening brace but to type a tab followed by the first line of the loop body.

A1.6.4. Unstable layout

Some programmers take great pride in lining up certain columns in their code.

firstRecord = readInt("First record:");
lastRecord  = readInt("Last record:");
cutoff      = readDouble("Cutoff:");

This is undeniably neat, and we recommend it if your editor does it for you. But don't do it manually. The layout is not stable under change. A new variable name that is longer than the preallotted number of columns requires that you move all entries around.

firstRecord    = readInt("First record:");
lastRecord     = readInt("Last record:");
cutoff         = readDouble("Cutoff:");
marginalFudgeFactor = readDouble("Marginal Fudge Factor:");

This is just the kind of trap that makes you decide to use a short variable name like mff instead.

The javadoc comments are unfortunately an example of unstable layout. Although there is no technical reason for it, the javadoc utility requires that each line in a documentation comment starts with a * . This makes it difficult to edit the comment, and it may well discourage programmers from doing so. With the javadoc comments, you have no choice. But with your own comments, simply format them 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, then facts win over beauty.