Code conventions
Formatting
-
Close braces go on their own line.
-
No lines longer than 120 characters, including Javadoc comments.
-
Wrapped lines should align with the expression at the same level on the previous line.
-
Wrapped lines should be broken after operators, not before.
-
Prefer braces with control flow statements.
-
Prefer aligned wrapped lines.
-
Prefer aligned wrapped parameter lists.
Whitespace
-
Two spaces for indents, no tabs.
-
Do not use spaces around parenthesis.
-
Use spaces after control flow keywords.
-
Prefer using blank lines to separate logical blocks of code, but do not be excessive.
-
Prefer not following casts with a blank space.
Structure
-
Do not use package imports (e.g.
import java.util.*
) -
Static fields must appear at the top of a class, before any other code.
-
Within a class, definitions should be ordered as follows:
Class (static) variables
Instance variables
Constructors
Methods
Javadoc
-
Public and protected methods and fields must have Javadoc.
-
Don't include your e-mail address in
@author
tags. -
You may omit
@return
tags for getters as long as you include a summary which begins with the word "Returns". -
Private methods do not require Javadoc but may have partial Javadoc if it adds valuable information.
Comments
-
Only use line comments within code, never block comments.
-
Prefer comments on their own line, rather than trailing, unless the latter is more readable.
-
Prefix line comments by a space
// like this
.
Variables
-
Prefer initializing variables when they are declared, rather than C-style declaration before use.
-
Always use final fields when possible.
Control Flow
-
Prefer multiple return statements over additional control flow logic.
-
Prefer switch statements over multi-clause if-then statements.
API Design
-
Give variables and methods meaningful names. Keep these short but don't use abbreviations. Follow standard names when possible.
-
Prefer final classes and final protected methods for non-final public classes, this reduces the surface area of the public API.
-
Avoid non-final protected variables in public classes. Prefer protected getters over protected variables when protected fields are necessery in public classes.
-
Minimize the API. Don't make everything public just because you can.
-
Don't expose implementation details unless there is a clear need: allowing subclassing means that the behaviour of protected methods becomes part of the contract of the public AP.
-
Avoid unnecesary abstraction. While you're encouraged to avoid brittle designs, it's unlikely that an API designed for "future use" will have the correct API without any code which actually uses it.
public class Foo extends Bar { public static void main(String args[]) { try { for (int i = 0; i < args.length; i++) { System.out.println(Integer.parseInt(args[i])); } } catch (NumberFormatException ex) { e.printStackTrace(); } } }
Created on , last edited on