Java Coding Style Guide

The size, age, and complexity of software is growing. Programmers now spend more time reading, maintaining, and enhancing code than they do writing original code. Therefore, it is critical that a professional programmer not only be able to write efficient and correct code, but it must also be written in a style that others can understand.

Coding standards are used by an organization to help everyone work more reliably together, improve quality, reduce development time, and allow quicker maintenance. Your guiding principle when writing code should be whether the reader will easily understand what you mean and what the code does. Well-designed, well-written code is a joy to debug, maintain, and enhance.

We will use a subset of Sun Microsystem’s Java Coding Conventions. You are expected to follow these conventions for all source code you develop for this course. Refer to How To Write Javadoc Comments for tips on the appropriate use of Javadoc tags.

Code Layout

Consistent layout of the source code not only improves readability but provides a professional appearance.

  • Use four spaces for indentation. Set your editor to automatically expand the TAB character to 4 spaces
  • Avoid lines longer than 72 characters.
  • Split statements longer than 72 characters into multiple lines by placing carriage returns after commas and operators.
  • Printed source code should not have lines that wrap.
  • Indent compound statements such as loops and branching statements. See example below.
  • Indent nested if statements as you would a switch statement. See example below.
  • Put the opening brace ‘{‘ on the same line as the class header, method header, conditional statement (if, switch), and loops.
  • Indent the closing brace ‘}’ at the same level as the corresponding class header, method header, conditional statement, and loops.

Comments

  • Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. Avoid duplicating information that is clearly evident in the code.
  • Javadoc comment must begin with /** and end with */

Class Headers

All source files should begin with a class header that lists the class name, version information, and author. Use Javadoc@author and @version tags where appropriate. See sample code below.

Method Headers

Provide headers for every method that includes horizontal lines to make the header visually distinctive. Use two blanks lines before each method header. Use Javadoc @param, @return, and @throws tags where appropriate. See sample code below.

Block Comments

Single line comments appear before ‘interesting events’ such as loops and branching statements. Provide a blank line before the comment and indent it with the code it describes. See sample code below.

If used, trailing comments at the end of lines should fit neatly within the 72 character line.

Declarations

  • Provide one variable declaration per line and provide javadoc comments before each declaration. See sample below.
  • Place declarations only at the beginning of blocks. One exception to the rule is indexes in for loops.
  • Declare instance variables at the top of the class definition (do not instantiate the object).
  • Instantiate instance variables in the class constructor (do not declare it).
  • Declare and initialize local variables at the start of a method.

Statements

  • Each line should contain only one statement.

White Space

Blank lines improve readability by setting off sections of code that are logically related.

  • Use a blank line before each method header.
  • Use a blank line before each comment.
  • Use a blank line between local variables declared in a method and its first statement.
  • Use a blank space around operators.

Naming Conventions

Naming conventions make programs more understandable by making them easier to read.

  • Class names should be a noun and begin with a capital letter. Keep the name simple and descriptive.
  • Method names should be verbs and begin with a lower case letter.
  • Variable names should be short yet meaningful. Avoid single character names, except for loop variables.
  • Variables defined as final or intended to serve as a constant should be in ALL CAPS.

Programming Principles

The following recommendations help prevent common errors and reinforce strong software design principles.

  • Avoid making instance or class variables public without a good reason.
  • Use instance variables for data that is part of the object state.
  • Use local variables within methods if the data is not part of the object state.
  • Strive to have a single return statement at the end of a method. However, there can be legitimate exceptions to improve readability or efficiency.
  • Avoid using break statements within loops and if statements. However, there can be legitimate exceptions to improve readability or efficiency.
  • Strive to keep methods short and perform a single task (less than 20 lines). This is a software engineering principle called high cohesion.
  • Avoid numeric constants. Instead, define a named constant at the top of the block. For example,

    final int MONTHS = 12;

  • Error messages and output should be clear and consistent.
  • The graphical user interface (GUI) should have a professional appearance.

Sample Source Code (with JavaDoc comments)

JavaDoc comments are only provided immediately before class definitions, methods, and instance variable declarations. Traditional Java comments should be used within the body of a method as necessary.

/*****************************************************************

Graphical representation of a six sided die with various controls over the appearance. Current value is constrained between 1 and 6.

@author Joanne Programmer

@version Winter 2007

*****************************************************************/

public class Dice extends Panel {

     /** current value of the die */

     private int myValue;

     /** current size in pixels */

     private int mySize;

     /** number of miliseconds between rolls */

     private int myDelay;

     /** color of the dots */

     private Color myColor;

     /** background color */

      private Color myBackground;

/*****************************************************************

Constructor creates a die of specified size X size pixels

@param size the length of each side in pixels

*****************************************************************/

public Dice(int size) {

     // initialize the die and determine display characteristics

     mySize = size;

     dotSize = mySize / 5;

     setBackground(Color.white);

     myColor = new Color(0,0,0);

     myColor = Color.black;

      setLayout(null);

      myValue = (int) (Math.random()*6)+1;

}

/*****************************************************************

Default constructor creates a die of size 100 X 100 pixels

*****************************************************************/

public Dice( ) {

        this(100);

}

/*****************************************************************

Set the delay in milliseconds between frames of the animation. Default value is 250.

@param msec milliseconds to delay

*****************************************************************/

public void setDelay (int msec) {

    myDelay = 0;

    if (msec > 0)

            myDelay = msec;

}

/*****************************************************************

Display the current value of the die. Called automatically after rolling. There is no need to call this method directly.

@param g the graphics context for the panel

@return none

*****************************************************************/

public void paintComponent(Graphics g)  {

    //ask my parent to paint needed components super.paintComponent(g);

    // paint dots based on current value

    switch (myValue)  {

    case 1:

         g.fillOval (middle, middle, dotSize, dot);

         break;

    case 2:

         g.fillOval (left, left, dotSize, dotSize);

         g.fillOval (right, right, dotSize, dotSize);

         break;

    case 3:

         g.fillOval (middle, left, dotSize, dotSize);

         g.fillOval (middle, middle, dotSize, dotSize);

         g.fillOval (middle, right, dotSize, dotSize);

         break;

    case 5:

         g.fillOval (middle, middle, dotSize, dotSize);

        // the "break" statement is intentionally omitted here

        // fall through and paint four more dots

    case 4:

         g.fillOval (left, left, dotSize, dotSize);

         g.fillOval (left, right, dotSize, dotSize);

         g.fillOval (right, left, dotSize, dotSize);

         g.fillOval (right, right, dotSize, dotSize);

         break;

    case 6:

         g.fillOval (left, left, dotSize, dotSize);

         g.fillOval (left, middle, dotSize, dotSize);

         g.fillOval (left, right, dotSize, dotSize);

         g.fillOval (right, left, dotSize, dotSize);

         g.fillOval (right, middle, dotSize, dotSize);

         g.fillOval (right, right, dotSize, dotSize);

          break;

     }

  }

}

Additional References



Page last modified February 6, 2024