Java Style

These guidelines are consistent with Sun's Code Conventions and Google's coding standards for Java.

Above all be consistent and clear.

Programs that check style:

See the on-line version: Java analyzer.

Checkstyle Checks

Some checks that may not be immediately obvious.

A. Identifiers

  1. All identifiers should have meaningful names---meaningful to people who do not know about the program. Occasionally, single letter loop indices like i for an int or o for an Object are acceptable. But do not overlook other possibilities like row or column.
  2. Class names must begin with a capital letter. (Hence files names begin with a capital letter.) The names of all instance methods and fields must not begin with a capital letter.
  3. Method and local variable names must begin with a lower case letter.
  4. Constants (static final member fields) must be all upper case letters and digits.
  5. Package names must be all lower case letters.
  6. Avoid abbreviations; never omit letters of a word to shorten an identifier.
  7. Avoid overly long identifiers, say greater than 20 characters or so.
  8. Although identifiers can differ only by capitalization in Java, never take advantage of this.
  9. Choose names for different identifiers that are "psychologically distant" in order to avoid confusion. Compare:
          disk_1     disk_2      disk_3
          smallDisk  mediumDisk  largeDisk
          
  10. Nouns should be used for classes; verb phrases for methods. For example,
          void free ()
          int assign ()
          float multiply ()
          void rescale ()
          void printTitles ()
          int  rollTwo ()
          void correctTable ()
          
    Functions that return a boolean value often begin with is
          boolean isEmpty ()
          boolean isAllZero ()
          
  11. Getter and setter methods should look like this:
          void setField (int field) { this.field = field; }
          int  getField ()          { return field;       }
          
  12. Interface names often end in "able," especially if they have one method: calculable, changeable, chargeable, commensurable, committable, communicable, compellable, computable, doable, igniteable, implementable, movable, paintable, pluggable, printable, realizable, runnable, serializable, terminable, throwable, tolerable, traceable, transferable, transfusable, transmittable, transposable, transportable, traversable, triable, usable, variable, venerable, etc.
          interface Computable {
             int compute (String x, float y);
          }
          

Hungarian notation uses leading (or occasionally) trailing tags that identify the type of the object. "Avoid ``Hungarian''-style naming conventions which encode type information in variable names. They may be systematic, but they'll screw you if you ever need to change the type of a variable. If the variable has a small scope, the type will be visible in the declaration, so the annotation is useless clutter. If the variable has a large scope, the code should modular against a change in the variable's type. In general, I think any deterministic algorithm for producing variable names will have the same effect." Larson's C Coding Style (The term Hungarian refers to the nationality of Charles Simonyi, a programmer at Microsoft who wrote a doctoral thesis in the 1980's called "Program Identifier Naming Conventions").

I am not a big fan of camelCase (aka camelBack, sulkingCamelCase). Compare with BiCapitalization (aka InterCaps), sTuDLyCaPs, etc., at the article on Wikipedia. I'd prefer to separate words by underscores (wide case). It looks better to readers (the underscore is the space-which-is-not-a-space) and can be enforced syntactically. Compare [a-z][a-zA-Z]* with [a-z]+(_[A-Z][a-z]*)*. Capitalization can then be reserved for distinguishing larger syntactic namespaces. Also, underscores work better with occasional acronyms, like ICBM_missile. But that is not the true way in Java.

B. Comments

  1. Comments should be helpful, clear, concise, and grammatically correct.
  2. Comments should be formatted appropriately.
          /*
             This
             comment
             wastes a lot of vertical space.
          */
          
  3. Do not restate the obvious. For example,
          i = i + 1;   // Add one to i
          
    Answer the question why you are doing it.
          i = i + 1;   //  Prepare for next record in list
          
  4. Comments should be indented to the same margin as the code they pertain to.
          // Loop comment
          for (;;) {
          }
          
    Not
          // Loop comment
             for (;;) {
             }
          

C. White Space

  1. Newlines should be indicated by either NL, or CR followed by NL.
  2. Use blank lines to separate logically related parts of the program.
  3. Use spaces judiciously to help the reader understand a complex line. For example, compare
          while (i<dataCount&&data[i]<target) {
          
    with
          while (i<dataCount && data[i]<target) {
          
  4. Use spaces judiciously to align similar or related program parts For example, compare
          private boolean hasExcess () { return dataCount>MAXIMUM; }
          private boolean hasShortage () { return dataCount<MINIMUM; }
          
    with
          private boolean hasExcess   () { return dataCount>MAXIMUM; }
          private boolean hasShortage () { return dataCount<MINIMUM; }
          
  5. Do not use excessive (i) vertical and (ii) horizontal white space.
  6. A space belongs before a '(' character (most of the time), and never afterward. A space belongs after a ')' character (most of the time), and never before.
  7. A space (or new line) belongs after the ',' or ';' characters, and never before.

D. Indentation

  1. Indentation should be 3 or 4 spaces. Less than 3 spaces does not leave enough visual contrast and more than 4 spaces wastes valuable horizontal space. The Java coding conventions say to use 4 spaces.
  2. Whatever the number of columns is chosen, that number should be used consistently whenever indentation is called for.
  3. Do not put the tab character in your programs, because applications interpret it differently.

E. Line Breaks

This convention for formatting control constructs is known as K&R (for Kernighan and Richie).
  1. Generally, there should be exactly one statement per line. (Although dependent on the overall developing environment, make lines less than 90 characters.)
  2. The opening bracket '{' should be on same line as the if, else, for, while, do, and switch keywords. (Sometimes known as Egyptian brackets.)
  3. Format of the while statement
          while (k<=j) {
             statements;
          }
          
  4. Format of the if statement
          if (...) {
            statements;
          } else if (...) {
            statements;
          } else {
            statements;
          }
          
  5. A for statement should have the following form:

          for (initialization; condition; update) {
             statements;
          }
          
  6. The rare for statement with an empty body should be written:

          for (initialization; condition; update) /* DO NOTHING! */ ;
          
  7. Format of the try statement:

          try {
             statements;
          } catch (ExceptionOneClass e) {
             statements;
          } catch (ExceptionTwoClass e) {
             statements;
          } finally {
             statements;
          }
          
  8. A switch statement should have the following form:

          switch (condition) {
          case ABC:
             statements;
             /* FALLS THROUGH! */
    
          case DEF:
             statements;
             break;
    
          case XYZ:
             statements;
             break;
    
          default:
             statements;
             break;
          }
          
  9. Always use brackets even when the body of a compound construct is just one statement.
          for (int space=0; space<indent; space++) {
             System.out.print(" ");
          }
          
    Get in the habit of doing this and you will have less trouble modifying your own code. Experienced programmers may be forgiven for occasionally breaking this rule in situations where the entire construct fits comfortably on one line.
          for (int space=0; space<indent; space++) System.out.print(" ");
          
  10. When you must break a very long expression across a line, follow these guidelines:
    1. Break after a comma.
    2. Break before an operator.
    3. Prefer higher-level breaks to lower-level breaks.
    As for indenting the next line ... the Java code conventions say to indent 8 spaces (two indenting units).

    In mathematical text always break mathematical formulas before a binary operator when the formula is displayed. (When the formula is in the text of the paragraph, then break after the operator.) Thus spoke Knuth.

F. Visibility

  1. Restrict the visibility of variables and other identifiers as much as possible. Move the declaration of local variables to the point of first use.
  2. Declare the index variables of loops in the for construct.
          for (int i=0; i<a.length; i++) {
             statements
          }
          
  3. Avoid methods that depend on instance variables and non-local variables.

G. General

  1. Initialization of variables:
    1. Initialize all variables at the point of declaration;
    2. use meaningful default values;
    3. if it comes to that, initialize objects to null, even though that is is redundant.
    4. In no case, initialize a string variable to a string that is never used.
  2. Use constants instead of variables as much as possible. In other words, favor final local and instance variables over non-final. Over 85% of local declarations should be final.
  3. Don't assign to method parameters; declare them to be final.
  4. Favor static over non-static methods, fields, and classes.
  5. Avoid comparing boolean constants or assigning boolean constant values to variables.
  6. Order the conditions in a test meaningfully. Use if(variable == constant) instead of if(constant == variable). No "Yoda conditions" (see New Programming Jargon).
  7. The extension of a Java source file name must be .java (no capital letters).
  8. Array types: use String[] args not String args[]. Its the form the works in most contexts, i.e., in a method's return type. Though the following is legal, don't use it.
          int x, y[]; // Avoid; use two declarations
          
  9. Follow the standard order of modifiers:
    1. Methods: [public|protected|private] -> abstract -> static->final->synchronized->native->strictfp
    2. Fields: [public|protected|private] -> abstract -> static->final->transient->volatile

H. Assert

Document your code by using the assert statement.
  // counter-clockwise is a left turn
  private final boolean leftTurn (Point p) {
     assert stack.size()>1; // must be at least two points on the stack
     return Triangle.isCCW ((Point)stack.get(1), (Point)stack.get(0), p);
  }
 // No place for file, so create new disk
 final Disc d = new Disc (discs.size()+1);
 assert (length<=discCapacity); // assume any 1 file can always fit on empty disc
 d.add (length,name);
 discs.add (d);

I. Design

Write simple and robust code.
  1. Do not write the essentially same code twice; use functions and procedures.
  2. Avoid multiple exits from loops.
  3. Avoid introducing boolean "flag" variables.
  4. Try to have exactly one return at the end of functions.
  5. Do not use System.exit()
  6. One class per file (inner classes excluded).
  7. Try to keep classes limited to 50-90 lines.
  8. Try to keep methods limited to 5-30 lines.
  9. Use packages to modularize complex programs.
  10. Use exception handling to handle uncommon cases.
  11. Don't handle exceptions unless the procedure can fix the problem or unless the procedure is responsible for reporting errors.
  12. Don't raise or catch NullPointerException; it is always evidence of a bug in the program
  13. Report errors and handle I/O in the main program.
  14. Avoid OS dependent behavior, e.g., Unix-centric constants "\n", "/", etc.
  15. Favor immutability. (Item 13, Block, 2001)
  16. Avoid string concatenation (except when concatenation two or three strings), use StringBuilder (StringBuffer is synchronized and so is less efficient). (Item 34, Block, 2001).
  17. Favor interfaces to reflection. (Item 35, Block, 2001).

Ryan Stansifer <ryan@cs.fit.edu>
Last modified: Tue Jan 17 15:49:58 EST 2012