Style Conventions  

Coding Style

Introduction

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. A program that "works" is not necessarily a good program; A good program is a program that is written in a comprehensible, modular, and readable style. For a small program such as the ones you write in your first steps, the way in which the program is written may seem unimportant and meticulous. However, in real life programmers often work as part of a group on a program of hundreds of thousands of lines. Moreover, the life-cycle of a program is usually long and the program should be maintained long after its original creators have left the project. As a result  a programmer often finds herself maintaining a program of thousands of lines written by several generations of programmers she is not familiar with. Understanding a computer program written by another person is always a hard task, but if the program is written in poor style the task is best described as a nightmare.

Most programmers would define 'style' as the things which relate to the appearence of the program, or in other words, how the program "looks": the naming of the various entities in the program (variables, classes, methods, etc.), the documentation and comments that appear in the program,  the indentation that is used in the program, and other technical details which relate to the structure of the program. It would perhaps be better to think about style as "the things in a program which a compiler doesn't really care about - but (most) programmers really do". Whether or not you chose the best name for your variable, added documentation, or indented your program - the compiler would be tolerant. Other programmers (and - believe it or not - even you, when you re-encounter your good old code) would definetly not.

The intention of this document is to present you with several guidelines that (we hope) will give you good programming style habits. You should keep in mind one thing: as the old jewish joke goes, if you ask 100 programmers to define their style guidelines, you'll get 100 (and perhaps even more than 100) different opinions. Well, the situation is not that liberal, but there's one golden rule about style: being consistent. If you decide upon a certain style scheme (and as a beginner we don't leave you much choice in deciding), use this scheme throughout your program, and maintain it throughout every program you write. It would have been nice if all programmers would have agreed upon style conventions, but as we have argued, this is not always possible. C++ programs, for example, have a wide variety of style conventions, depending on the literature and education the programmer has been raised upon. The great thing about Java, is that an agreed upon convention (or at least a minimal set of conventions) had quickly evolved. These conventions are adpoted by most Java programmers (and originate at the book The Java Language Specification by Gosling, Joy and Steele.)

Indentation

Read the discussion about white space characters in Lewis & Loftus p. 36.

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

We recommend the following indentation rules:


Class Names

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 well chosen, it will be difficult to find the class, understand the relationship between the different classes the program consists of, and to remember the name of the class when it is needed.

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, and this is also true in real-life programming). 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 The rules for meaningfulness of class names apply also for variables. There are several additional notes. Methods
  Implementation 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 work. Documentation comments on the other hand, are intended for programmers who want to use the code as a whole. They are not interested in understanding the inter working of the code.

There are 3 forms for writing comments in Java:

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


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 ends 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 chapter 18 in James Gosling, Bill Joy, Guy Steele, The Java Language Specification. For details on using the javadoc tool for generating automatic API documentation look here.

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.

Another example:

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 {





    // ...





}
Every public and protected method must be preceded with 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, document all the parameters 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 frequently happens for the constructors of the class).

// from class Deck





    /**


     * Shuffles the Deck.


     */


    public void shuffle() {





        // ...


    }
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() {





        // ...


    }
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;