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.
Sample program written in good style. This gets a grade of A+.
Sample program receiving a grade of C.
Sample program receiving a grade of F.
Sample industrial code. 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.
Carefully use indentation 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. The exact amount of the indentation is not important, but be consistent throughout your program. Use blank lines to improve readability. 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();
}
}
}
Note that additional spaces have been inserted inside of parentheses to increase readability. This is optional. Two additional alternatives are to align comments with the code rather than indent and to put starting braces on their own line.
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 rquired 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();
}
}
}
It does not matter which stylistic conventions you choose. This is simply a matter of individual preference. However, it is very important to be consistent throughout your program. Mixing of styles is confusing to the reader and looks sloppy.
Put only one Java statement on a line.
sum = val + length; i++; // Avoid this
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 or indented one level deeper. They are generally preceded by a blank line.
if( list.isEmpty( ) ) {
// Boundary condition for empty list.
d_head = new Node( vale, null );
// Or indent like this but don't mix the two styles. Be consistent.
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
Each programming assignment should begin with a block comment in the
following form. Feel free to add simple html tags (such as
<br> and <b> to improve the readability of the web page
generated by Javadoc.
/** * 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)
*
*/
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> {
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.
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 much 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. Declaring all local variables at the start of a block is to be avoided.
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. Avoid this.
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:
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).
This document was written by Kye Hedlund.
Some of the above items are adapted from.
Code
Conventions for the Java Programming Language. Sun Microsystems web
site.
Effective Java, Joshua Bloch, 2001, Addison-Wesley
The Java Programming Language, Fourth Edition, Arnold, Gosling and
Holmes, 2006, Addison-Wesley.