Naval Postgraduate School
Java Style Guide

This page is a (revisited) mirror page last modified

published
(original author's agreement pending) by marc.meurrens@acm.org (http://homepages.ulb.ac.be/~meurrens)

URL of the original document
http://vislab-www.nps.navy.mil/~java/course/styleguide.html
by N.P.S., the Naval Postgraduate School (java@nps.navy.mil(JAVAPage)) "A special thanks goes to John Falby for his effort in helping to develop a NPS CS style guide. The Java style guide is mirrored from the NPS CS C++ style guide used and developed by John Falby."

URL of our page(s) on "Java OO Design & Coding Standards"
(where this document is referred as detailled below):
http://www.ulb.ac.be/esp/ip-Links/Java/joodcs/index.html
[back]

The Navy Java Style Guide
is essentially intented for the students of the N.P.S. School (some recommandations are not exportable outside the school). It is available on our site as a revisited mirror (original author's agreement pending) of http://vislab-www.nps.navy.mil/~java/course/styleguide.html (Last Updated 8 JUL96) by the Naval Postgraduate School (java@nps.navy.mil(JAVAPage)). The Java style guide is mirrored from the NPS CS C++ style guide used and developed by John Falby.
Unfortunately, some features available only in C++ (enum, typedef, cout, etc) were NOT removed! So, handle this text with care!!!

Pre-prepared links (to this document)

A list of approx. 66 "pre-prepared" links to this page is available at URL http://www.ulb.ac.be/esp/ip-Links/Java/joodcs/naval-LinksTo.html.
These links are (or will be) used in other pages related to "OO design and Coding Standards".

Revisions

Index

Naval Postgraduate School
Java Style Guide

A table of content of this MIRROR page is available here.

1.0 General

The purpose of the style guide is not to restrict your programming innovation, but rather to impose a consistent format for your programs. This will help you debug and maintain your programs. While that might not seem like a big deal now, it will in the long run, since the focus of this course is to build a foundation for the later courses.

2.0 Visual Layout

You should format your program making use of page boundaries and blank lines to separate code groups, functions and groups of logically related blocks. As a general guideline, no method or sub-class should be longer than one page, and formatting should ensure that it prints out on one page. There are exceptions, such as breaking a method up to fit a page may be poor design and worse than writing one that is too long.

Output from a program should be both informative and professionaly formatted. A person reading the output should be able to determine for himself whether he believes that the program works reasonably, without knowing the internal details of the program.

A printed page should be no more than 72 columns and 60 lines (12 point font).

3.0 Indentation and Whitespace.

Indentation is used to highlight the block structure of the code and must therefore be used consistently. The proper use of white space and indentation makes the structure of the program evident from the layout of the code. You must use proper indentation, which in this class is three spaces. We strongly recommend the use of spaces vice tabs. Printers and other users might have different tab spacing.

Vertical whitespace (i.e. blank lines) helps set off blocks of code and can increase readability of the code. Code with no vertical whitespace becomes very busy and hard to follow.

A method of class name and its associated braces are aligned in the left most column, and all other code is indented from there. The closing brace will always be on a line by itself and aligned with the beginning of the block opening brace. Braces used to block code will be indented consistently with the rest of the code.

Comments will be indented consistently with the block of code they describe.

The following is an example:


/***********************************************************************
* method: my_method
* Return Value: none
* Parameter: counter - the current program count value
* Purpose: This method  is an example of the indentation requirements
***********************************************************************/

void my_method(int counter)
{
   //comment indented consistent with the 
   //block of code it refers to
   if(counter > MAX_VALUE)
   {
      counter = MAX_VALUE;
   } //aligned ending right brace with statement beginning the block

   switch(counter)
   {
      case 1: //the first case
         //something interesting
         break;
      case 2: //the second case
         //something interesting
         break;
      default:  //what it does if no other branch is taken
         //something interesting
         break;
   } //aligned with statement beginning the block

   return; //not absolutely necessary, but consistent to end with one
}

There is one exception to the rules concerning indentation:

    When readability is increased. For example, the following code fragment does not strictly follow the three space indentation rule, but readability is increased:


   System.println.out("Welcome to the Units of Measurement Conversion Program!!");
   System.println.out("You enter the number of gallons and the program");
   System.println.out("will return the number of each of the following");
   System.println.out("equal to that many gallons:");
   System.println.out("   Quarts");
   System.println.out("   Pints");
   System.println.out("   Cups");
   System.println.out("   Liters");

   

4.0 Control Structures

The use of braces is required for all control structures.

Avoid the use of continue and break in loops.

Always use a default case in switch statements. Use a break to end all cases (including default) in a switch statement.

The use of //end if, //end while, and //end switch comments after the corresponding ending right brace is optional but highly recommended.

Indentation and formats for control structures are as follows:

//** the use of braces is required for all control structures


if (expression)
{
   statement(s);
} 
else if
{             //an else-if clause is not required
   statement(s);
}
else
{                //an else clause is not required
   statement(s);
}//end if 


for (expression; expression; expression)
{
   statement(s);
}//end for 


do
{
   statement(s);
} while (expression);


while (expression)
{
   statement(s);
}//end while 


switch (expression)
{
   case constant:
      statement(S);
      break;         //always have a break statement after each case
   case constantTwo:
      statement(S);
      break; 
   default:          //always have a default case
      statement(s);  //statements not required
      break;
}//end switch 

5.0 Naming

Variables will have meaningful names/identifiers. This must be balanced against using names which are too long, which can obscure the code. (A variable name greater than around fifteen characters is approaching the "too long" limit.) The only exception to this is for loop iteration counters. These special case variables can have names like "ix", "jx", etc. Single letter variables or constants should not be used. The exception is when it is a common practice to identify something with a single letter. An example of this is the coordinate axis (X, Y, and Z).

An identifier consisting of multiple names shall have each name set off. This is done by making the first letter of each name part capital (e.g. redCarColor), or by using underscores between parts (e.g. red_car_color), but not both (e.g. red_Car_Color).

Do not use the letter `l' (lower case `L'), `o', or `O' in names unless they are part of normal words. This is to avoid confusion with the numbers 1 and 0.

All normal identifier names must be in lower or mixed case. (method, typedef, variable names, class, struct, union, and enum tag names)

Enum elements must be in all CAPS, but instantiations can be in lowercase.

Names with a leading or trailing underscore are usually reserved for system purposes, and may not be used for any user-created names with the exception of preprocessor defines.

Avoid names that differ only in case, look similar, or differ only slightly.

Avoid redefining names of standard identifiers (e.g cout).

Names of methods with return type of void should reflect what they do (printArray).

Names of methods which return something should reflect what they return (initialize).

All global variables will start with "G_". Globals used only in a single class will be defined in that class, be declared as static, and start with "L_". const names are not considered global variables.

Define TRUE, FALSE and NULL, and use them by name as opposed to using 1 and 0 explicitly.

Avoid using absolute path addressing when referring to files. Use relative addressing based upon the location of the executable.

Specify only the file names (i.e. without paths) for includes and libraries.

6.0 Classes

Classes are declared in the following order:

    public member methods

    public data members

    protected methods

    protected data variables

    private methods

    private data members

7.0 Methods

The main() method shall be declared as the last method in the class, ie:


 public static void main(String args[])
                          throws java.io.IOException
 {
     return

 }

Avoid multiple return statements in the same method.

Test the return values of methods. It is not uncommon for a method to fail and an error manifest itself much later in the code.

Each method (starting with the method comment) must be separated from other text/code by at least two blank lines.

8.0 Globals

For the most part, globals are bad and do not use them. However, there are a certain cases when globals might be used. All use of globals must be completely documented and justified.

9.0 Files

All Java source files will have a "java" extension and the prefix before the extension will be the same name as the class with in the file.

10.0 Comments

Comments can be divided into two general categories, strategic and tactical. Strategic comments are used to give the reader a general overview of what is going on. These comments appear at the top of the files and before the function code. Strategic comments tend to be written in a prose style. Tactical comments are designed to explain tricky areas of code, what parameters do, and hints about the control flow of the program. These comments are imbedded in the code and tend to be shorter and in bullet format. The javadoc will be used to develop documentation files.

If you use proper naming, block structure, indentation, and straight forward programming, your code will be mostly self documenting. This is what you should strive for. Keep comments simple. Do not attempt to explain the obvious. Do not use banner-like comments. Avoid decoration.

Use the Java (C++) "/*"......"*/"construct for all comments. This will allow you to block out sections of code with the old comments.

Implementation comments should be intermixed within the code. Usage comments will precede the code, normally in the file or function comment.

Each class and method declaration must have a description in comments preceding it. The declaration will contain a comment pertaining to usage, and the definition should contain comments relating to the implementation.

At a minimum, each source class file must have a descriptive comment at the top as follows:


/****************************************************************************
* File: _________________ 
* @author _________________ 
* @version  1.2 31 Jan 96
* @see awt.BaseWindow
* @see awt.Button
* @param background color 
* @return value of I is returned
* Date:
* CS2971 Section ____ 
* Project # __ 
* Operating Environment: ________________
* Compiler: _____________________
* Description: _________________________ 
* Algorithm: (Give a step-by-step alogorithm)
***************************************************************************/
Each method or subclass must have an appropriate comment giving a brief description using the following format:



/****************************************************************************
* method: countTime
* @return Value: time corresponding to program count
* @param Parameter: count - the current program count value
* Purpose: This method takes a counter and converts it to the lapsed time
***************************************************************************/

 public countTime()
 {
   float time = count / TIMER;

   return time;
 }

Each class source file shall terminate with an end of file comment of the form:

//end of file test.java

11.0 Miscellaneous

Always use the most appropriate operator or construct.

Always use the principle of least privilege (grant only that access necessary to perform the task and no more).

All long int literals must have the `L' suffix (e.g. 40000L). Numerical constants ("magic numbers") must not be coded directly. The only allowable exceptions are for 0, 1 or -1, and those which are not "likely" to change. For example, the following code which is determining if a number is even uses "2" since it would not be likely to change:


int isEven(int number)
{
   /*  result is 0 if odd, 1 if even */
   int result = (number % 2) + 1;

   return result;
}

Numerical constants must have a comment explaining the value if it is not evident by the name.

Enumeration types must be used to declare constants that have a discrete set of values. A comment must be provided indicating what the start value is.

You must test floating point numbers with <= or >=. Never use exact comparisons with floating point numbers, even when comparing to 0.0f. The appropriate means of comparison is to define a value that represents the maximum difference two values may differ by and be considered equal.

You may not use any libraries except those included with the standard compiler.

You may not use any public domain or shareware code. All code must be your own.

You should test your code. It should produce the correct results for normal test conditions as well as boundary conditions.

Good design and clarity take precedence over optimization. (To a point)

Do not declare or use more variables than are necessary.

No line of code should exceed 72 characters (including blanks).

If you open a file for reading/writing, close the file as soon as you are finished reading from/writing to it.

Note: A special thanks goes to John Falby for his effort in helping to develop a NPS CS style guide. The Java style guide is mirrored from the NPS CS C++ style guide used and developed by John Falby.

Index
this (original) page is located at
http://vislab-www.nps.navy.mil/~java/course/styleguide.html
java@nps.navy.mil
Last Updated 8 JUL96
Naval Postgraduate School © 1996

Brussels, last modified
mirror ("Last Updated 8 JUL96 - Naval Postgraduate School © 1996") of the the Naval Postgraduate School (java@nps.navy.mil(JAVAPage))
published by marc.meurrens@acm.org (http://homepages.ulb.ac.be/~meurrens)
original URL: http://vislab-www.nps.navy.mil/~java/course/styleguide.html
current URL: http://www.ulb.ac.be/esp/ip-Links/Java/joodcs/NavyStyleGuide.html
internet programming Links: http://www.ulb.ac.be/esp/ip-Links (ip-Links)
Université Libre de Bruxelles: http://www.ulb.ac.be (ULB)
La Cambre - Architecture: http://www.lacambre-archi.be
Belgian JAVA User Group: http://www.bejug.org (BeJUG)
 
Use this form to send your feedback and/or submit a link
(please, replace sample texts by appropriate data before submitting!)
From
your e_mail :
your URL :
To sja@bejug.org ; java@nps.navy.mil ; meurrens@ulb.ac.be
Subject
Link
Comment
 
Conventions used in these pages:
html file, text file or java or CPP source located on our site
download area (on our site) or file to be downloaded (use the right button of your mouse)
document on a belgian academic or scientific site
document (on another site) or link to be fixed or link we didn't visit/evaluate; documents indicated with their full URL will be displayed in their own "top" window.
ftp download or file to be downloaded (use the right button of your mouse)
indicates a "mailto" link.
Click on the separator to reach a higher level in the page or site hierarchy.
 

back home e_mail ULB ESP ip-Links La Cambre BeJUG