Coding Standards for Java Programs

Version 1.10.4

This document gives some rules of thumb for writing programs in good style. No set of rules can cover all possible situations; use common sense always. The purpose of good style is to make programs easily readable and intelligible. This has at least two important benefits: it helps us avoid errors when writing the program initially, and we or others who subsequently need to revise the program won't be confused.

How to Develop Programs

Coding Standards

Standards are listed under the chapter where they first become applicable.

Chapter 1: Basics

  1. Each source code file should begin with a header comment which shows the file name, author's name and email address, course, date, and purpose of the program. Example:
    /* File:    Hello.java
       Author:  Jane Doe (janedoe@example.edu)
       Course:  INFO-I211
       Date:    January 1, 2010
      
       Purpose: This program prints the message "Hello, Java!"
                ten times.
    */
    Alternatively, the header comment may be written using the // or /** ... */ comment notation.
  2. Indent code to show program structure. For example, all but the first line of a class definition should be indented, and all but the first line of a method definition should be further indented. See Listings 1.1-1.3 in Java Software Solutions for examples of good and bad formatting.

    Indent with two or four spaces for each level of structure, and be consistent.

    Do not use the TAB character to indent. (But you may use the TAB key if it inserts spaces instead of tabs.)

    Hint: Some text editors and most IDEs can help you indent. In Emacs: (a) TAB indents the current line. (b) C-j starts a new line and indents it. (c) For Emacs in Java mode, the Java menu has an "indent line or region" command.

  3. Write no more than one statement per line.
  4. No line should exceed 80 characters, which is the standard width of a terminal or printed page. Lines longer than 80 characters will either "wrap around" or be cut off when viewed or printed at the standard width, making them ugly and/or unintelliglble. Split complex statements across lines at sensible breaking points, and indent the continuation lines.

Chapter 2: Data and Expressions

  1. Code should be clear, simple, and straightforward to the extent possible. Avoid obscure and bizarre usages and unnecessary complexity.
  2. Code that is (nevertheless) not self-explanatory should be documented with comments.
  3. Use meaningful and appropriate variable names. Variable names like x are suitable only for abstract numbers (e.g., a program that computes the square root of x) and geometric coordinates. Variable names should accurately suggest what the variable represents. A variable that represents a person's age, for example, should be named age rather than weight.
  4. Use spaces to separate the parts of expressions and lists. For example, 5 * (x + 1) is better than 5*(x+1).
  5. Use parentheses if they will help to clarify complex expressions.

Chapter 3: Using Classes and Objects

  1. Use blank lines to separate distinct sections of code.

    But do not overuse blank lines. For example, don't double space a section of your program, or double space your entire program, Use blank lines to separate what needs to be separated.

  2. Use "CamelCase" for class names: begin with a capital letter and capitalize every subsequent word in the class name. Do not use underscores. Examples: PrettyGoodScanner, AverageGuy, DecimalFormat.
  3. Use "camelCase" for variable names: begin with a lower-case letter and capitalize every subsequent word in the variable name. Do not use underscores. Examples: width, conversionRate, inchesOfRain.

Chapter 4: Writing Classes

  1. Organize the class structure in this way: field declarations first, followed by constructors, then methods.
  2. Use "camelCase" for method names, and continue using it for variables — both local variables and fields (instance and class variables), except for variables declared final. Examples: getHeight, setHeight, inchesToMeters.
  3. Use "UPPER_CASE" names for constants, i.e., variables declared static. Use underscore characters to separate words within the name. Examples: VERSION, TAX_RATE, SPEED_OF_LIGHT.
  4. Variables that are used only by one method should be declared as local variables, within the method, rather than instance variables.
  5. Avoid using the same name for a local variable and an instance variable (shadowing).
  6. Use encapsulation. Normally, instance variables should be declared private and should be accessible only through the methods provided by the class. Use an accessor method to provide read access, and/or a mutator method to provide write access. Some instance variables may not need access from outside the class.
  7. If a method is getting too complex, divide it into subproblems, and define a helping method for each of the subproblems. Generally, several short methods are better than a single long method.
  8. Use methods to avoid code repetition. It is hard to give strict rules about this, but here are some rules of thumb:
    1. One complex line repeated two or more times.
    2. Two or more simple lines repeated two or more times.
  9. Use methods to improve code clarity. Sometimes the meaning of a few lines, or even one line, of code can be made clearer by wrapping it in a method definition and giving it a name. This may be true even if the lines are unrepeated.
  10. Declare methods that are part of the class's interface public; declare other, helping methods private.
  11. Use meaningful and appropriate method names, just as you would use meaningful and appropriate variable names.
  12. Write a comment above each method (a "header comment") that explains what its parameters are, what it does, what value it returns, unless this information is perfectly obvious from reading the method's name, return type, and parameter list. The header comment should also explain what conditions must be true before the method is called (preconditions), and what conditions the method guarantees to be true when it returns (postconditions).
  13. Indent the statements within the body of a method.
    Hint: use the TAB key in Emacs to indent a line, or use C-M-\ to indent a region.
  14. Use blank lines to separate methods.

Chapters 5–6: Conditionals and Loops

  1. Indent statements in the body of control structures (if, while, for, do/while, and switch statements).
    (See the indenting hint under chapter 1.)
  2. Avoid the continue and break statements, except for break statements required in a switch statement.
  3. Avoid redundant tests in if statements. For example,
    if (size > 100)
      System.out.println("Large");
    else if (size > 50)
      System.out.println("Medium")
    else
      System.out.println("Small");
    is preferable to
    if (size > 100)
      System.out.println("Large");
    else if (size > 50 && size <= 100)
      System.out.println("Medium")
    else if (size <= 50)
      System.out.println("Small");
  4. Use boolean variables and expressions outside of the context of an if statement to simplify code. For example,
    return (x == y);
    is preferable to
    if (x == y)
      return true;
    else
      return false;

Chapter 8: Arrays

  1. Use named constants, instead of just numbers, to specify array sizes. Example:
    final int NUM_STUDENTS = 35;
    Student [] scholar = new Student[NUM_STUDENTS];
  2. Don't space between the name of an array and its subscript. For example, write scholar[i], not scholar [i].
  3. Use array initialization lists if the initial values of elements are known when an array is created and the number of elements is small. Examples:
    int [] nums = new int[] {1, 3, 7, 12, 19};  // recommended
    int [] nums = {1, 3, 7, 12, 19}; // alternate

Chapter 9: Inheritance

  1. Use private, protected, and public qualifiers to strike a balance between encapsulation and accessibility.
  2. Design of class hierarchies:
    1. Keep common features as high in the hierarchy as possible. This maximizes software re-use and minimizes the needs of software maintenance.
    2. Only use subclasses when there is an "is-a" relationship.
    3. There is no one best class hierarchy for all purposes; think carefully about what design works best for the application.
  3. Override methods to make exceptions to general rules.
  4. In particular, routinely override the equals and toString methods.
  5. Use abstract classes or interfaces to specify behaviors that are required but not (yet) defined.
  6. Avoid shadowing inherited instance variables.
  7. Let each class manage its own data, using constructors, accessors, and mutators.

Chapter 10: Polymorphism

  1. Use polymorphic references (either by inheritance or by interfaces) to increase flexibility of methods. This means using a supertype (superclass or interface) as the declared type of a variable and using subtype (subclass or implementing class) objects for the actual values.
    1. Polymorphic parameters of methods.
    2. Polymorphic array elements.

References

For further reading. Some of these references provide dull summaries of common industry practices. Others are gems of reflective insight. The recommended reading may or may not agree with the rules listed above. If you find yourself inclined to dissent, please discuss it with me. — Gregory D. Weber


Summary of Recent Revisions

?