Java Program Style Guidelines

The following are guidelines for formatting and preparation of your programs for programming assignments. These are the minimum requirements for a program to be considered in good style. They should be followed carefully.

Style is also important in the early version of your program as well as the version you finally turn in, because debugging is much easier when the code is clearly written, nicely laid out, and well documented. TAs and lab attendants have been instructed not to give assistance with sloppy or undocumented programs.

Before you think that the A+ program is excessively neat and commented, take a look at this industrial quality code. Our A+ standards really are minimum requirements for a good program. This code is from the Gnu release of the Java Collections Framework.

 

Coding Conventions

Indentation is used so that the physical layout on the page reflects the logical structure of code. Each block of code should be indented, and the individuals lines of a block should be left aligned. Use blank lines to improve readability. Eclipse will take care of the indentation for you. Select 'Source->Format'. Use this for all code you turn in. The following member function illustrates these guidelines.

  public static void reverse(SinglyLinkedMiniList list) {
    SinglyLinkedMiniList.MiniListIterator itr = 
	  new SinglyLinkedMiniList.MiniListIterator(list);
		
	// itr walks from head of list to last element required.
	while(itr.hasNext()) {
	
		// Position inner_itr one past required placement.
		SinglyLinkedMiniList.MiniListIterator inner_itr = 
			(SinglyLinkedMiniList.MiniListIterator) itr.clone();
	
		// inner_itr walks from the successor to the tail of itr.
		while(inner_itr.hasNext()) {
			if(itr.get().equals( inner_itr.get()))
				inner_itr.remove();
		} 
	} 
  }

Put only a single Java statement on a line.

	sum = val + length; i++;	// Avoid this

Commenting Conventions

Comments explaining your design and coding decisions are a vital part of every programming assignment. As in any form of writing, you must consider your audience. Your programming assignments has two very different audiences. The Java code itself is interpreted by the computer to produce the results of your program. Getting the correct result is very important, but it is only one part of the program. You also have a human audience. Another programmer must be able to understand the design decisions you made, how they are reflected in your code, and how your code works. In an industrial environment, this is essential for maintaining and enhancing software. In the academic environment, you must make the grader happy.

There are three styles of comments: block, single-line, and trailing. Block comments are used to provide descriptions of each programming assignment, class definitions, and member functions.

/**
 * This is a block comment. It is preceded by a blank comment line to set it apart
 * from the rest of the code. An asterisk "*" begins each line except the first. It
 * begins with "/**" (note the double asterisk) and ends with "*/".
 */

Short comments can appear on a single line indented to the level of the code that follows. To improve readability, they are generally preceded by a blank line.

if( list.isEmpty( ) ) {

	// Boundary condition for empty list.
	d_head = new Node( vale, null );

	// Circular link.
	d_tail = d_head;
}

End-of-line comments appear on the same line they describe, but should be shifted far enough to the right to separate them from the statements.

			
	p.d_next = new_node;    // Last node links to new node

A. Programming Assignment

Each programming assignment should begin with a block comment in the following form.

/**
* Program Insert assignment number and name 
* 
* @author Insert your name 
* Due Date Insert due date 
*  
* Class Comp Insert class number Instructor Insert name
* Section Insert section number 
* 
* Pledge: I have neither given nor received unauthorized aid 
* on this program. (signature on file) 
*  
*/

B. Class Definition

Each class definition should begin with a block of comments that briefly explain what the class does.

/**
* Class SinglyLinkedMiniList
* Singly linked implementation of a MiniList (subset of the Java List interface).
*
*/
public class SinglyLinkedMiniList implements Iterable<Object> {

C. Member Function

Each member function should be preceded by a block of comments in the following style. To allow proper processing by the javadoc tool, it is necessary to begin the comment with "/**" and a blank comment line must precede the annotations (@param, etc.).

 
 /**
  * v put in ith element and returns previous value in ith element
  * Pre: 0 <= i <= size() 
  * Post: get(i) == v AND return_value == old_list.get( i )
  *
  * @param i index into list
  * @param v value to put into list
  * @return previous value in ith element
  * @throws IndexOutOfBoundsException if i < 0 or i > size() 
  */
  public Object set( int i, Object v ) {

This header block must succinctly but thoroughly describe the contract between the method and its client. For each parameter, include a @param tag that explains the value represented by the parameter. Include a @return tag explaing the value returned unless it has a void return type. Finally, have a @throws tag for each exception thrown by the method. The standard format for the text following @throws is the exception name folloed by the word "if" and a description of the conditions under which the exception is thrown.

D. Within a member function

Use comments to explain each local variable. There are a few exceptions where the usage is obvious (such as i as index variable, count to count occurrences, etc.), but when in doubt, comment it.

Named constants should be used to associate identifiers with all values that have special meaning in your program. For example:

      final int MAX_LINE_SIZE = 80; // Maximum legal length of an input line. 
      final String SENTINEL = "END"; // Indicates end of input. 

The proper use of constants make it easier to understand your program and easier to change to accomodate new requirements.

Minimize the scope of your local variables. A local variable should be declared close to where it is first used. Avoid declaring all local variables at the start of a block of code.

Each block of code that is more than a few lines long or performs a nontrivial task should be immediately preceded by a comment telling what it does (WHAT, not HOW).

	// Find predecessor of ith element.
	Node p = d_head;
	for(int j = 1; j < i; j++) 
		p = p.d_next;

Avoid commenting the obvious. It clutters up the page. For example

     sum = 0; // Set sum to zero. AVOID THIS

This comment tells the reader nothing that she did not already know.

Label with comments your "Boundary Conditions" and your "Typical Case ".

There are lots of rules for coding and commenting, but many of them follow from two general principles, your programs should be:


Naming Conventions

In general, names should be mnemonic, explaining what they are. It is easier to understand sum, Stock, or MAX_VALUE rather than s, stk, or mx. In addition to being mnemonic, Java has a well-established set of conventions for forming names so that the name often tells the reader that type of object it represents. Adhering to these makes your programs easier to understand and grade. Naming conventions fall into two categories: typographical and grammatical.

The typographical conventions refer to the formatting of names used in your program

 

Identifier Type Examples
Class or Interface Timer, Stock, HttpServlet, Deck
Method or Data Member remove, ensureCapacity, getRank
Constant Data Member MAX_CARDS, TRACE, NEGATIVE_INFINITY
Local Variable i, xref, count, houseNumber, player_war
Package war, program4, com.sun.medialib

 

Class and interface names consist of one or more words, with the first letter of each word capitalized. Abbreviations should be used sparingly and long names are common. The emphasis is on clarity rather than brevity. Acronyms may be in all uppercase or with only the first letter capitalized (e.g. HTTPURL or HttpUrl). Member functions and data members follow the same convention as class and interface names, except that the first letter is lower case. An exception is constants, whose names should consist of one or more uppercase words separated by the underscore character. Local variables have more leeway than other names. Single characters and abbreviations are allowed, but don't sacrifice clarity.

The grammatical rules are more flexible than the typographic conventions. Classes and interfaces are generally named with a noun or noun phrase, for example, Card or BufferedReader. Member functions that perform an action are often named with a verb or verb phrase, for example, append or displayShape. Methods that return a boolean often begin with "is", for example, isEmpty, isEnabled, isDigit. Member functions that return or change a single attribute are often named getAttribute or setAttribute (e.g. getMaximum, setLength, setTime). Methods that convert the type of an object are often called toType (e.g. toString, toArray). C++ programmers may be accustomed to prefacing data members with "d_" or just "_" (e.g. d_count, _temperatures, d_largest).

 

Assertions and Exceptions

Use exceptions to indicate an error by the client. Most commonly this is a precondition violation. For example

	// @requires length > 0
	public void memFn( int length ) {
		if( length <= 0 ) 
			throw new IllegalArgumentException();

Us of the assert statement should be restricted to catching inernal program bugs. A failed assertion means that the program has a bug, but when an exception is thrown, the client has violated the contract. Exceptions allow us give more meaningful error messages and, in some cases, take corrective action. A failed assert simply crashes the program.

The following exceptions are built into Java and should cover most, if not all, the needs of Comp 401 / 410.

 

Exception Occasion for use
NullPointerException Parameter value is null where prohibited
IllegalArgumentException Non-null parameter value violates a precondition
IllegalStateException Object state is in valid
IndexOutOfBoundsException Index parameter value is out of range

 

Some of the above items are adapted from