PROGRAM STYLE GUIDE

In this page: Braces | Whitespace | Indentation | Naming | Commenting Guide     Related Pages: Example

Good programming style isn't meant for the compiler, which only requires that you use the correct syntax for the programming language. Programmers use good programming style to ensure that their source code is easily read and understood by people. These people typically are members of a program development team and others who maintain or enhance the code. Good style is particularly important when an author leaves a project. Then only the source code remains to communicate the author's intentions.

Good style will also help you develop your code more efficiently and minimize bugs. A programmer's personal style develops over their career. It is to your advantage to take the time now to establish good programming practices. Your pesonal style must fit within a number of conventions followed by the industry. In CS302, we'll concentrate on the following aspects of style:


Braces {}

Recommendation: Always use braces even when they are not required. Selection and looping statements do not require braces if their body contains only one statement. A defensive programming practice is to use braces anyway. This helps avoid inadvertent errors while developing your code. However examples we provide and those in the text will sometimes leave out unnecessary braces.

Requirement: Line up braces. There are several common styles. Pick one style and use it consistently throughout your source files.

 Style Example
1
statement header 
{
    body
    body
}
This style is recommended and used by our text.
2
statement header {
    body
    body
}
This style is acceptable and used by many programmers.
3
statement header
    {
    body
    body
    }
This style is discouraged, but it is sometimes used by others.

Whitespace

Whitespace is essential for making source files readable. Meaningful parts of code are grouped together by using the whitespace as a separator. Whitespace is composed of horizontal whitespace (i.e. space and tab characters) and vertical whitespace (i.e. newline/return character makes blank lines).

Requirement: Use vertical whitespace to organize your source code into meaningful parts. For example, use blank lines to separate methods from each other, data members from methods, and import statements from comments. Blank lines are also used to separate groups of statements from eachother to make the major steps of an algorithm distinguishable in a method's body.

Requirement: Use tabs/spaces to indicate the level of nesting (see indentation).

Requirement: Use horizontal whitespace to organize each line of code into meaningful parts. There are many personal styles of spacing within a line. It is bad style to not use spaces within a line. For example:

good style result = 5 * Math.abs(xCoord - ++yCoord) / (11 % -time)
bad style! result=5*Math.abs(xCoord-++yCoord)/(11%-time)
good style for (day = 11; day < 22 && !done; ++day) {
ok style for (day=11; day<22 && !done; ++day) {
bad style! for(day=11;day<2&&!done;++day){

Indentation

Requirement: Lines should be of reasonable length. 80 columns including whitespace is typical. Going a little longer is okay but excessive line length is not acceptable.

Requirement: Use tabs/spaces to indicate the level of nesting. Indentation occurs in fixed-width intervals. Today most source code editors automatically indent for you typically using an interval of four spaces. It doesn't matter how much you indent as long as you are consistent throughout your source files. See the example, which uses four spaces per indentation.

Level 0: The following items are not indented:

  • File Header Comments
  • import statements
  • Class Header Comments
  • Class Declarations

Level 1: The following items are indented once:

  • Data Member Comments
  • Data Member Declarations
  • Method Header Comments
  • Method Declarations

Level 2+: Other statements are indented at least twice, which is the level of a method's body. Beyond level 2 you should indent once each time a statement is nested inside the body of another statement (see examples below). Always indent whether or not the control structure uses braces (see braces).

Statement Indentation Example
if & for loop
if (day == 31) 
{
    monthTotal = 0;
    for (int week = 0; week < 4; ++week) 
    {
        monthTotal += receipts[week];
    }
}
Indent each time a statement is put in the body of another statement.
chained if-elses
if (month >= 1 && month <= 3)
    quarter = 1;
else if (month >= 4 && month <= 6)
    quarter = 2;
else if (month >= 7 && month <= 9)
    quarter = 3;
else
    quarter = 4;
Combine else with nested if; indent if and else clause bodies to one level only.
switch form 1
switch (month) 
{
    case 2:
        daysInMonth = 28;
        break;
    case 4:
    case 6:
    case 9:
    case 11:
        daysInMonth = 28;
        break;
    default:
        daysInMonth = 31;
        break;
}
An alternative is not to indent the case and default clauses.
switch form 2
switch (month) 
{
    case 2:  daysInMonth = 28;
             break;
    case 4:
    case 6:
    case 9:
    case 11: daysInMonth = 28;
             break;
    default: daysInMonth = 31;
             break;
}
This is the form the text uses.

Proper Naming in Java

Requirement: Source files are named the same as their class and ending with the extension .java. The spelling and capitalization must match, e.g. class Example would be in a file named Example.java

Requirement: Java requires you to follow these naming RULES when choosing names:

  • Names must consist of only letters, digits, dollar signs ($), and underscore (_) characters
  • The first character in a name cannot be a digit.
  • Reserved words cannot be used.

Requirement: Follow these naming CONVENTIONS when choosing names:

  • Do not begin names with dollar sign ($) or underscore (_) characters.
  • variable, method and package names begin with a lowercase letter, e.g. age, setAge, width, or computePerimeter
  • Class names begin with an uppercase letter, e.g. class Example, class Dice, or class Person
  • CONSTANTS are in all uppercase letters, e.g. MAX_WIDTH or DEFAULT_COLOR
  • namesWithMultipleWords use initial capitals to make subsequent words distinct, e.g. method setToolTipText, getX, or setColor. MULTI_WORD_CONSTANTS use an underscore to separate words as shown above.

Requirement: Use descriptive names. The name need not be long, but it must relate to the intended use. Short (i.e. 1 letter) names can be used for temporary variables and loop counters.

  • tableHeight is more descriptive than th. However, height can be used if it is clear that it refers to the height of only one thing in your program.

Use Symbolic Constants instead of magic numbers

Requirement: Define symbolic constants to avoid the need to use literal values like 7, 100, or 3.1415927 in calculations or comparisons.

Such values when found in code are often referred to as magic numbers as they do not have any meaning except if the programmer remembers what the number referred to. Unfortunately, a new programers, or your grader may not know or be able to figure out what such a number represents.  So, unless the number has only one meaning and everyone knows it, it is better to define a symbolic constant and use that name in your code.

Can I just describe the value in the comments? Describing the use of such values in comments is helpful, but not as useful as defining a named constant to assign the value to a recognizable name.

Examples:

/** Number of rows and columns in the game board */
public static final int BOARD_SIZE = 8;

/** Stores the maximum number of players */
public static final int MAX_PLAYERS = 4;

/** Stores the id number of this object */
public final int ID;

Note: instance (non static) fields in instantiable classes may be declared as constants (final) and those constants may be assigned values via the constructor.

Requirement: Follow naming CONVENTIONS for defining symbolic constants, specifically:

  • Use the field modifier final.
  • Use all uppercase letters for the name of the CONSTANT, e.g. MAX_WIDTH or DEFAULT_COLOR
  • Use an underscore to separate words in MULTI_WORD_CONSTANTS as shown above.

Requirement: Use descriptive names. The name need not be long, but it must relate to the intended use. Short (i.e. 1 letter) names can be used for temporary variables and loop counters.

  • BOARD_WIDTH is more descriptive than bw. However, width can be used if it is clear that it refers to the width of only one thing in your program.

Commenting Guide

Program comments are intended for programmers, and they are ignored by the compiler. We want you to develop good commenting style so we'll require the following:

File Headers

Requirement: The source file for the MAIN CLASS must have a main file header comment located at the beginning of the file containing the following:

///////////////////////////////////////////////////////////////////////////////
//                   ALL STUDENTS COMPLETE THESE SECTIONS
// Title:            (program's title / homework title)
// Files:            (list of source files / homework files)
// Semester:         (course) Summer 2017
//
// Author:           (your name)
// Email:            (your email address)
// CS Login:         (your login name)
// Lecturer's Name:  (name of your lecturer)
//
//////////////////// PAIR PROGRAMMERS COMPLETE THIS SECTION ////////////////////
//
//                   CHECK ASSIGNMENT PAGE TO see IF PAIR-PROGRAMMING IS ALLOWED
//                   If pair programming is allowed:
//                   1. Read PAIR-PROGRAMMING policy (in cs302 policy) 
//                   2. choose a partner wisely
//                   3. REGISTER THE TEAM BEFORE YOU WORK TOGETHER 
//                      a. one partner creates the team
//                      b. the other partner must join the team
//                   4. complete this section for each program file.
//
// Pair Partner:     (name of your pair programming partner)
// Email:            (email address of your programming partner)
// CS Login:         (partner's login name)
// Lecturer's Name:  (name of your partner's lecturer)
// Lab Section:      (your partner's lab section number)
//
//////////////////// STUDENTS WHO GET HELP FROM OTHER THAN THEIR PARTNER //////
//                   must fully acknowledge and credit those sources of help.
//                   Instructors and TAs do not have to be credited here,
//                   but tutors, roommates, relatives, strangers, etc do.
//
// Persons:          Identify persons by name, relationship to you, and email.
//                   Describe in detail the the ideas and help they provided.
//
// Online sources:   avoid web searches to solve your problems, but if you do
//                   search, be sure to include Web URLs and description of 
//                   of any information you find.
//////////////////////////// 80 columns wide //////////////////////////////////

Requirement: Source files for OTHER CLASSES must have a file header comment located at the beginning of the file containing the following (see example):

///////////////////////////////////////////////////////////////////////////////
//                   ALL STUDENTS COMPLETE THESE SECTIONS
// Main Class File:  (name of main application class)
// File:             (name of this class's file)
// Semester:         (course) Spring 2016
//
// Author:           (your name and email address)
// CS Login:         (your login name)
// Lecturer's Name:  (name of your lecturer)
// Lab Section:      (your lab section number)
//
//////////////////// PAIR PROGRAMMERS COMPLETE THIS SECTION ////////////////////
//
// Pair Partner:     (name of your pair programming partner)
// Email:            (email address of your programming partner)
// CS Login:         (partner's login name)
// Lecturer's Name:  (name of your partner's lecturer)
// Lab Section:      (your partner's lab section number)
//
//////////////////// STUDENTS WHO GET HELP FROM OTHER THAN THEIR PARTNER //////
//                   fully acknowledge and credit all sources of help,
//                   other than Instructors and TAs.
//
// Persons:          Identify persons by name, relationship to you, and email.
//                   Describe in detail the the ideas and help they provided.
//
// Online sources:   avoid web searches to solve your problems, but if you do
//                   search, be sure to include Web URLs and description of 
//                   of any information you find.
//////////////////////////// 80 columns wide //////////////////////////////////

Class Header

Requirement: Each class must have a header comment located immediately before the class declaration containing the following (see example):

/**
 * (Write a succinct description of this class here. You should avoid
 * wordiness and redundancy. If necessary, additional paragraphs should
 * be preceded by <p>, the html tag for a new paragraph.)
 *
 * <p>Bugs: (a list of bugs and other problems)
 *
 * @author (your name)
 */

This form for the class header is the standard for documenting java programs. It is refered to as a "javadoc" comment because it is used by the javadoc program to automatically generate documentation in HTML format. You will not be required to run javadoc on your programs but it is a useful capability to know about. For more information about javadoc, you should visit Sun's website: How to Write Doc Comments for the Javadoc Tool

Method Header

Requirement: Each method must have a header comment located immediately before the method declaration (see example). Include the information below but leave out parameter and/or return-value comments if the method has none. The method description must state preconditions and postconditions. Preconditions are requirements that must be met before entering the method, and postconditions are results from executing the method. Do not state the obvious such as "an object needs to be created before calling this instance method". Instead specify things that may be overlooked or unexpected.

/**
 * (Write a succinct description of this method here.  If necessary,
 * additional paragraphs should be preceded by <p>, the html tag for
 * a new paragraph.)
 *
 * @param (parameter name) (Describe the first parameter here)
 * @param (parameter name) (Do the same for each additional parameter)
 * @return (description of the return value)
 */

This form for the class header is the standard for documenting java programs. It is refered to as a "javadoc" comment because it is used by the javadoc program to automatically generate documentation in HTML format. You will not be required to run javadoc on your programs but it is a useful capability to know about. For more information about javadoc, you should visit Sun's website: How to Write Doc Comments for the Javadoc Tool

Variable Declarations

Requirement: Variable declarations must be commented briefly describing their use. This includes object and primitive variable declarations of:

  • class data members and constants
  • instance data members and constants (see example)
  • local variables and constants (see example)

Requirement: Primitive variable declarations must also specify their range of values if it is a subset of the full range for their data type. (see example).

Temporary variables and loop counters do not need to be commented.

Other Comments

Requirement: Use comments within the body of methods to:

  • highlight the major steps of your algorithm
  • explain long calculations or conditions
  • clarify convoluted or unusual code
  • mark locations where you suspect a bug may exist
  • mark locations where improvements or enhancements are planned

Do not use comments in methods to explain things that are obvious to programmers. For example, it is not useful to provide comments such as "this assignment statement assigns 22 to the variable x". Instead use comments to point out things that are not immediately evident or to highlight sections of code.

© 2000-2010 Jim Skrentny,
© 2001-2005 Deb Deppeler,
© 2007 Beck Hasti