Java Language Coding Guidelines

(Modified from Cay Horstmann's textbook)

1  Basic Style Conventions

2  Academic Integrity

Every program requires a signed cover sheet - Pay attention to this. You will be held accountable to the requirement of doing your own work!

 
Program______________________________

Programmer _________________________________
Academic Integrity Pledge

- All source code and documentation used in my program is either
  my original work, or was derived, by me, from the source
  code published in the textbook for this course or presented in class.
  Any source code in this project that is derived from code published 
  elsewhere is documented as such so the original author receives due 
  credit.
- I have not used source code obtained from another student,
  or any other unauthorized source, either modified or unmodified.
  I have not helped another student write their program by providing
  a printed or electronic copy of my solution.
- I have not discussed coding details about this project with anyone
  other than my instructor. I understand that I may discuss the
  concepts of this program with other students, and that another
  student may help me debug my program. However, the responsibility
  to write each program belongs solely to the program's author.
- I have violated neither the spirit nor letter of these restrictions.


_______________________________________  Date___________________
Signature of programmer

3  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:

 
/**
   COPYRIGHT (C) 2004 Harry Hacker. All Rights Reserved.
   Classes to manipulate widgets.
   Solves CS209 homework assignment #1
   @author Harry Hacker
   @version 1.01 2004-09-15
*/

4  Classes

Each class should be preceded by a class comment explaining the purpose of the class. This should start as an overview, then expand on some of the implementation details. In particular, describe how you intend to implement some of the features or represent some of the more important properties.

Leave a blank line after every method.

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. Do not use the default visibility (that is, package visibility) or the protected attribute.

Avoid static variables (except final ones) whenever possible. Be sure to adequately document reasons for using static variables in your class.

5  Methods

Every method starts with a comment in javadoc format. Include descriptions of parameters and return values.

 
/**
   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 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. This rule forces you to break up complex computations into separate methods.

6  Variables and Constants

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

 
{  
   double xold; // Don't
   double xnew;
   boolean more;
   . . .
}

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
      . . .
   }
   . . .
}

In general, do not define two variables on the same line:

 
int dimes = 0, nickels = 0; // Don't

Instead, use two separate definitions:

 
int dimes = 0; // OK
int nickels = 0; 

In Java, constants must be defined with the keyword final. If the constant is used by multiple methods, declare it as static final. It is a good idea to define static final variables 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 -1, 0, 1, and 2 is considered magic:

 
if (p.getX() < 300) // Don't

Use final variables instead:

 
final double WINDOW_WIDTH = 300;
. . .
if (p.getX() < WINDOW_WIDTH) // OK

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 365s, 364s, 366s, 367s, and so on, in your code.

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

7  Control Flow

7.1—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

7.2—The for Statement

Use for loops only when a variable runs from somewhere to somewhere with some constant increment/decrement:

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

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.

 
a = a / 2;
while (count < ITERATIONS) // OK
{  . . .
   System.out.println(xnew);
}

7.3—Nonlinear Control Flow

Avoid the switch statement, because it is easy to fall through accidentally to an unwanted case. Use if/else instead. Of course, you are still welcome to use a switch if you think it is the best way to present your solution.

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

7.4—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

Beginners often make this mistake "to keep the compiler happy". If the current method is not appropriate for handling the exception, simply use a throws specification and let one of its callers handle it.

8  Lexical Issues

8.1—Naming Convention

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

Names must be reasonably long and 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 ctr, c, cntr, cnt, c2 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, result, . . . ).

8.2—Indentation and White Space

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

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

Use a blank space around every binary operator:

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

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

Leave a blank space after (and not before) each comma or semicolon. Do not leave a space before or after a parenthesis or bracket in an expression. Leave spaces around the ( . . . ) part of an if, while, for, or catch statement.

 
if (x == 0) y = 0;

f(a, b[i]);

Every line must print without wrapping, so check your printed output and make adjustments before turning in your final versions of your programs. If you must break a statement, add an indentation level for the continuation:

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

Start the indented line with an operator (if possible).

  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 ( .........................................................
   && ..................
   || .......... )
{  
   . . .
}

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

8.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) {
   System.out.println(a[i]);
   i++;
}

Doing so makes it hard to check that the braces match, but is still acceptable.

8.4—Unstable Layout

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

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

This is undeniably neat, but 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 = other.firstRecord;
lastRecord  = other.lastRecord;
cutoff      = other.cutoff;
marginalFudgeFactor = other.marginalFudgeFactor;

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

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                  *
 ********************************/

It looks neat, but it is a major disincentive to update the comment. If your editor adds some decorative asterisks automatically, great... but do not waste your time creating them manually.

Instead, format long comments like this:

 
/* comment
   more comment
   more comment
*/

or 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.