Honors Introduction to Computer Science I

CS181 Fall 2008


Coding Conventions

Block Comments

Each class declaration should be preceded by a block comment that lists the class description, date, and author(s). For example,

/*
 * This class implements the quick sort algorithm.
 * 
 * 03/25/08
 * 
 * Stan Rosenberg
 *
 */
public class QuickSort {
...
}

Each method declaration should be preceded by a block comment describing what the method should do. Describe the arguments, the return value (if any) and pre/post conditions. You are encouraged but not required to state the pre- and post-conditions. When you do state the pre- and post-conditions, use 'requires' for pre-conditions and 'ensures' for post-conditions. For example,

/*
 * Partitions the sub-array a[p..r] such that the elements to the left
 * of the pivot are smaller than the pivot, and the elements to
 * the right of the pivot are larger than the pivot.
 * Returns the pivot value.
 * 
 * requires  - a != null && 0 <= p <= r < a.length
 * ensures   - contents of a is a permutation of its initial contents,
 *	       and the result is some integer, piv, such that
 *	       p <= piv <= r && a[p..piv] <= a[piv] && a[piv] <= a[piv..r]
 *
 */
int partition(int[] a, int p, int r) {
...
}

Short Comments

In addition, to the class and method block comments (which are absolutely compulsory) there will be many occasions when a statement (or a sequence of statements) is not self-explanatory. In those cases short comments may suffice. For example,

/* Allocate new array data of 10 elements */
ArrayData a = new ArrayData(10, 100);
/* Create random elements and shuffle them */
a.scramble();

Be sensible about when to use comments. Comments like

/* increment i */
i++;
do not add to the readability whereas the lack of comments in this case
return .5*Math.sin(2*Math.PI*(1/per)*((double)i/44100));
makes it very difficult for those other than the authors understand what the intended meaning of the expression might have been.

Other Conventions

For a complete specification of Java code conventions, see conventions. When it comes to indentation and line-breaking, a particular choice may either add to or detract from readability. The Java code conventions address these and a host of other stylistic issues. Adhering to these conventions is especially useful in the industry since they are widely adopted throughout the Java community.

For this course, however, you are required to follow at the minimum, the conventions outlined in the previous two sections --- comments. Additionally, we strongly encourage that you follow the Java naming conventions. As far as statement indentation, line-breaking, variable naming, etc. goes, make sure that you adhere to something consistent throughout your whole program. (E.g., use the style of the textbook, Java code conventions, or invent your own.)


Credits: Stan Rosenberg Valid HTML 4.01! Valid CSS!