Java Style Guide

Comments

  1. Methods should have javadoc comments explaining the behavior, parameters (using @param tags or otherwise), and return type.

  2. Methods that return non-void values must describe them in their Javadoc comment either with a “@return” tag or in a phrase in running text that contains the word “return”, “returning”, or “returns”.

  3. Each Javadoc comment must start with a properly formed sentence, starting with a capital letter and ending with a period.

Basic information that are better contained in a javadoc comment.

image-20211004183304628

Identifiers

  1. Names of static final constants must be in all capitals (e.g., RED, DEFAULT_NAME).
  2. Names of parameters, local variables, and methods must start with a lower-case letter (Camel-Case Style), or consist of a single, upper-case letter.
  3. Names of types (classes), including type parameters, must start with a capital letter.
  4. Names of packages must start with a lower-case letter.
  5. Names of instance variables and non-final class (static) variables must start with either a lower-case letter or “_”.

Imports

  1. Do not use ‘import PACKAGE.’, unless the package is java.lang.Math, java.lang.Double, or org.junit.Assert. ‘import static CLASS.’ is OK.
  2. Do not import classes or members that you do not use.

Modifiers

Write any modifiers for methods, classes, or fields in the following order:

  1. public, protected, or private.
  2. abstract or static.
  3. final, transient, or volatile.
  4. synchronized.
  5. native.
  6. strictfp.

Do not explicitly modify methods, fields, or classes where the modification is redundant:

  1. Do not label methods in interfaces or annotations as “public” or “abstract”
  2. Do not label fields in interfaces or annotations as “static”, “public”, or “final”.
  3. Do not label methods in final classes as “final”.
  4. Do not label nested interfaces “static”.

Only static final fields of classes may be public. Other fields must be private or protected.

Classes that have only static methods and fields must not have a public (or defaulted) constructor.

Classes that have only private constructors must be declared “final”.

Avoiding Error-Prone Constructs

  1. Local variables and parameters must not shadow field names. The preferred way to handle, e.g., getter/setter methods that simply control a field is to prefix the field name with “_”, as in

    public double getWidth() {
         return _width;
    }
    
    public void setWidth(double width) {
        _width = width;
    }
    
  2. Do not use nested assignments, such as “if ((x = next()) != null) …”. Although this can be useful in C, it is almost never necessary in Java.

  3. End every arm of a “switch” statement either with a “break” statement or a comment of the form

    /* fall through */
    

Reference: https://sp19.datastructur.es/materials/guides/style-guide.html