Programming Style Guidelines

These styles guidelines are taken from the ones I've written for the 'Introduction to Computer Science' course.

When writing a computer program it is important to keep in mind that the program should not only run correctly, but also be written in a clear way so that other people can understand it.

The intention of this document is to present you with several guidelines that (we hope) will give you good programming style habits.

Notation: throughout the document, we color example of good style in green and examples of bad style in red.

Content

  1. Indentation
  2. Class names
  3. Variables names
  4. Comments
  5. Methods
  6. Documentation Comments

Indentation

The purpose of indentation is to emphasis the structure of the program - its division into blocks.

We recommend the following indentation rules:

Class names

In general picking up good names for your program elements (classes, methods, variables, ...) is a very important part of the documentation of your program. A good name for a class is the fastest way to describe what the class used for. Naming is particularly important for classes, because often people will use your classes as a whole (without looking in their implementation). If the names of your classes are not good, it will make it hard for them to: find the class they are looking for, understand the relationship between the different classes the program is made of and to remember the name of the class when they need to use it.

For many of the exercises, we will tell you the name of the classes you should use (we must have consistent names to enable automatic checking of the exercises). However, it is important that you should be aware of the guidelines for naming classes and you will need them for some of the exercises.

Here are several rules for naming classes:

Variable names

Apart from that most of the rules for classes names apply also for variables. We list them again with examples for variables. There are several additional notes.

Comments

There are two types of comments in Java: implementation comments and documentation comments. Implementation comments are intended for the programmer who maintain the code, he/she needs to understand how does the code works. Documentation comments on the other hand, are intended for programmers who wants to use the code as a whole. They are not interested in understanding the inter working of the code. They only need to understand what does it do and how to use it. This section give several guidelines for writing implementation comments. We discuss documentation comments later on.

There are 3 forms for writing comments in Java:

Guidelines about implementation comments:
(some of the guidelines below are taken from Lewis J. & Lottus W. / "Java software solutions" pp. 605)

Methods

Documentation Comments

Documentation Comments are special Java comments used to describe the API of a class or an
interface. Documentation Comments can appear before each class or interface declaration and
before each method, constructor or field declaration. A documentation comment begins with /**
and end with */. Below is an example of a class definition which includes documentation
comments.
/**
 * A FIFO queue that can hold arbitrary objects.
 * 
 * @author Shmulik London
 */
public class Queue {

    /**
     * Constructs an empty queue.
     */
    public Queue() {
        // some code here
    }

    /**
     * Inserts an item to the queue.
     * @param item The item to be inserted.
     */
    public void enque(Object item) {
        // some code here
    }

    // some code here
}
Documentation Comments may include plain text, HTML, and some special tags. For a detailed
description of Documentation Comments refer to: "The Java Language Specification" / James Gosling, Bill Joy, Guy Steele, Chapter 18. For details on using the 'javadoc' tool for generating automatic API documentation, refer the section about javadoc in the JDK Documentation Page.

Documentation Comments are intended for generating API documentation for your class. This means that they are intended for programmers who wish to use your class as a whole and need to understand its interface. They are not intended for the programmer who maintains the code! (for those we use regular comments) In this sense Documentation Comments in Java have a similar role as header files (.h files) have in C modules.

Use Documentation Comments only for entities that are part of your class public interface:

The class comment should open with a short sentence describing this class (its purpose), followed by a more detailed description of the use of the class. The implementation of the class should not be documented here, unless it affects the API of the class (in which case you should add a short note indicating this). If the use of the class is not obvious from the API, it is recommended to give an example for its use. At the end of the class documentation block, you should denote yourself as the author of the class and (if needed) add references to related classes or methods.

Examples: see Java's java.util.StringTokenizer API, source

package games.card_games;

/**
 * A Deck of cards. This class is intended for use in card games.
 * Each player holds a Deck (or more) of cards containing several
 * cards. The content of the Deck changes along the game.
 * <P>
 * Example:
 * <PRE>
 * Deck dealerDeck = Deck.createFullDeck();
 * dealerDeck.suffle();
 * Deck deck1 = new Deck();
 * Deck deck1 = new Deck();
 * while(!dealerDeck.isEmpty()) {
 *     deck1.addCard(dealerDeck.drawCard());
 *     if (!dealerDeck.isEmpty()) {
 *         deck2.addCard(dealerDeck.drawCard());
 *     }
 * }
 * </PRE>
 *
 * @author <A Href=mailto:londons@cs.huji.ac.il>Shmulik London</A>
 * @see games.card_games.Card
 * @see games.card_games.BridgePlayer
 */
public class Deck {

    // ...

}
Before every public and protected method there should be a documentation comment. The comment should begin with a short sentence describing the method, ending with a period ('.'). Only the first sentence (until the period) is displayed in the API's method index. The rest of the comment appears in the detailed list of methods (together with the first). If the first sentence is not enough for describing the use of the method, you can add several sentences of explanations. Explain only what the method does and NOT how it does it!. Avoid long documentation!
If you cannot describe the method in a single sentence (because it does more than one thing), it may be a good sign that you should split it into several methods, or reconsider your design.
// class deck continued

    /**
     * Adds a card to the top of the deck.
     */
    public void addCard(Card card) {

        // ...
    }
If the method gets more than one parameter or if the role of this variable is not clear from its name, use the @param tag to document the parameters of the method. In any case, if you document a parameter, then document all the parameters! and document them in the same order they appear in the method's signature. If two parameters are related you can document them in the same line.
// part of class Figure

    /**
     * Constructs a new Figure.
     * @param x,y The location of the top-left corner of the Figure.
     * @param width, height The dimensions of the Figure.
     */
    public Figure(int x, int y, int width, int height) {

        // ...
    }
When documenting the parameters of a method that is not void (and is not a constructor), also document its return value with the @return tag.

Do not worry if the sentence describing the method seems to add no information (Unless this sentence is not clear) - it probably indicates that your choice for the name of the method is good (This always happens for the constructors of the class, because they have an excellent name - they have none. More seriously, their function it is clear from their essence).

// from class Deck

    /**
     * Suffles the Deck.
     */
    public void suffle() {

        // ...
    }
If the method throws an exception (in particular if it is a RuntimeException you may expect) document the exception with the @exception tag.
// from class Deck

    /**
     * Draws a card from the top of the Deck.
     * @return A card from the top of the Deck
     * @exeption DeckEmptyException If the Deck is empty
     */
    public Card drawCard() {

        // ...
    }
Try your best in given the method a descriptive name. A good name is more important than good documentation, as the method name appear in everywhere it is used and also it is faster to read and understand.

In general most of the fields of a class will usually be private. Public fields make sense if they denote a public constant or they are part of a class which is a wrapper for several values (such as java.awt.Point). You should have a reason for defining a field as protected and a good one for defining it as friendly. In any case before every public or protected field you must put a short documentation comment. If you cannot describe the function of the field in one sentence it may be a good indication that it is not suitable for it to be public or protected (consider an access method instead). The style of documenting a field is as follows:

/**
 * The double value that is closer than any other to pi, the ratio of the 
 * circumference of a circle to its diameter.
 */
public static double PI = 3.14159265358979323846;