Java Coding Standards

General

Every programming department has some set of standards or conventions that programmers are expected to follow. The purpose of these standards is make programs readable and maintainable. After all, you may be the programmer who maintains your own code more than six months after having written the original. While no two programming departments' standards/conventions may be the same, it is important that all members of the department follow the same standards. Neatness counts!!!

In general we will follow the Code Conventions for the Java Programming Language as developed by Sun Microsystems. It is your responsibility to read, understand, and use these standards. In particular, graders will be looking for you to adhere to standards regarding:

  1. File Names
  2. Naming Conventions
  3. Indentation and use of Whitespace
  4. Comments

Comments are the programmer's main source of documentation.

From The Practice of Programming by Brian Kernighan and Rob Pike, page 23...

Comments are meant to help the reader of a program. They do not help by saying things what the code already plainly says, or by contradicting the code, or by distracting from the code with elaborate typographical displays. The best comments aid the understanding of a program by briefly pointing out salient details or by providing a larger-scale view of the proceedings.

Note that we will be discussing “documentation comments” in lab.

Naming

Class Comments

Every .java file should contain a “class header comment” describing the class within the file and containing other pertinent information. This comment must be a block comment that begins with /** and includes the following information. Some of this information will automatically be included when using Eclipse to create your .java files.

  1. A description of what the class represents or does
  2. The class invariant(s)
  3. The date the file was created (shown below after the @version annotation)
  4. Your name & UMBC email address (shown below after the @author annotation)
  5. The project number (shown below after the @project annotation)
  6. Your section number (shown below after @section annotation)

For example:

/**
 * This class models a traditional table
 * Class Invariants:
 *   - A table must have either 3 or 4 legs
 *   - A table must be round, rectangular, or oval
 * @version 9/22/05
 * @author Bob Smith <bsmith22@gl.umbc.edu>
 * @project CMSC 202 - Spring 2011 - Project 1
 * @section 02
 */
public class Table {
    /* ...class definition... */
}

Method Comments

Method comments are the primary form of documentation for the user of our class methods. It is important that this documentation be both complete and accurate, as it forms a “contract” between the class user and and the class implementer. These comments are sometimes referred to either as “documentation comments” or “interface comments.”

Each class method must have a comment that includes the following information. If you use Eclipse to write your code, it will add other important information for you (e.g. parameter names).

  1. A description of the task that the method performs, including any pre-condition(s) and post-condition(s).
  2. Each parameter should be identified and briefly described (shown below after the @param annotation). If there are any constraints on the parameters, say so.
  3. If the method returns anything, it should be identified and possible values mentioned where applicable (shown below after the @return annotation).
  4. If the method raises any exceptions, identify the exception(s) raised and note the conditions that trigger that exception(s).

A pre-condition is a statement giving the condition(s) that is (are) required to be true when the method is called. The method is not guaranteed to perform correctly unless the pre-condition is (are) true. It is NOT just a restatement of the parameter names and types. All methods must test for pre-conditions to the extent possible. Until we learn about exceptions, your instructor will tell you how to handle a violated pre-condition.

A post-condition is a statement describing what will be true when the method call is completed (assuming the pre-condition is met and the method completes).

For example, a method that calculates the area of a circle might have a header like this.

/**
 * Calculates the area of a circle given its radius
 * Precondition: the radius must be >= zero
 * Postcondition: the area is calculated or zero returned if the radius is < zero
 * @param radius: the radius of the circle
 * @return the calculated area of the circle, or zero if an invalid
 *         radius was supplied
 */
double circleCircleArea(double radius) {
   // handle unmet precondition
   if (radius < 0.0) {
      return 0.0;
   } else {
      return Math.PI * radius * radius;
   }
}

Block Comments

Unlike class and method level comments, block comments are intended for individuals that need to update, modify and maintain your code. As such, they should aid in the understanding of the code and clarify what non-straightforward or complex code is doing.

For example, the following code contains enough higher-level block documentation to help the reader understand what's going on. However, simple or self-explanatory statements (e.g. the three assignment statements that make up the swap on lines 8–10) are not (and should not) be documented.

public static void bubbleSort(int[] numbers) {
  // start at back, reducing length each iteration
  for(int i = numbers.length - 1; i > 0; i--) {
    // sweep though from 0 to current length
    for (int j = 0; j < i; j++) {
      // if these 2 adjacent numbers are out of order, swap
      if (numbers[j] > numbers[j+1]) {
        int temp = numbers[j];
        numbers[j] = numbers[j+1];
        numbers[j+1] = temp;
      }
    }
  }
}

A Larger Example

The following illustrates what a file that adheres to these standards might look like.

package proj1;

/**
 * Represents a modern motor vehicle consisting of a make (e.g. Audi),
 * model (e.g. A8), year of manufacture (e.g. 2011) and a paint color
 * (e.g. PaintColor.BLACK).
 * Class Invariants:
 *   - make, model, and paint color may not be null
 *   - vehicle year must be > 1900
 * @version 01/27/2011
 * @author Dwight Schrute <dwightschrute@umbc.edu>
 * @project CMSC 202 - Spring '11 - Project 3
 * @section 02
 */
public class Vehicle {

    private String make;       // Vehicle make (e.g. Audi)
    private String model;      // Vehicle model (e.g. A8)
    private int year;          // 4-digit year vehicle was produced (e.g. 2011)
    private PaintColor color;  // Vehicle color (e.g. PaintColor.Black)

    /**
     * Constructor - creates a new Vehicle instance
     * Preconditions:
     *   - make, model, and color must not be null
     *   - year must be > 1900
     * Postconditions: A vehicle object is created and its instance variables
     *                 initialized
     * @param make the make of the vehicle
     * @param model the model of the vehicle
     * @param year the 4-digit year the vehicle was produced
     * @param color the paint color of the vehicle
     */
    public Vehicle(String make, String model, int year, PaintColor color) {

        // ...code to perform error checking here...

        this.make = make;
        this.model = model;
        this.year = year;
        this.color = color;
    }

    /**
     * Checks to see if the vehicle qualifies as historic under
     * MD state law.
     * Preconditions: None
     * Postconditions: Returns true or false
     * @return true if the vehicle is considered historic, false
     *         otherwise
     */
    public boolean isHistoric() {

        boolean historic = false;

        // ...code to check to see if vehicle is historic here...

        return historic;
    }

    /**
     * Gets the color of the vehicle
     * Preconditions: None
     * Postconditions: Vehicle's color is returned
     * @return the current vehicle color
     */
    public PaintColor getColor() {
        return color;
    }

    /**
     * Updates the vehicle as having the new paint color
     * (i.e. the vehicle has been repainted)
     * Preconditions: New paint color is not null
     * Postconditions: Color is set to the new color
     * @param color: the new paint color
     */
    public void setColor(PaintColor color) {
        this.color = color;
    }

    /**
     * Gets the make of the vehicle
     * Preconditions: None
     * Postconditions: Vehicle make is returned
     * @return the make of the vehicle
     */
    public String getMake() {
        return make;
    }

    /**
     * Gets the model of the vehicle
     * Preconditions: None
     * Postconditions: Returns the vehicle's model
     * @return the model of the vehicle
     */
    public String getModel() {
        return model;
    }

    /**
     * Gets the year the vehicle was manufactured
     * Preconditions: None
     * Postconditions: Returns the vehicle's year
     * @return the year the vehicle was manufactured
     */
    public int getYear() {
        return year;
    }

    /**
     * Creates string of Vehicle instance variable values
     * Preconditions: None
     * Postconditions: Instance variable string has been created
     * @return string containing values of Vehicle instances variables
     */
    public String toString() {
        return color + " " + make + " " + model + " (" + year + ")";
    }

}