Where not explicitly overridden below, the Sun/Oracle Java Code Conventions apply. These are the default/fallback conventions.
This means, for example:
- Class/interface names start with a capital letter. All class and interface member names start with a lowercase letter, except constants, which should be in all caps and underscores.
- Always use curly braces around blocks, even for single statements.
- Curly braces go on the same line as the
if/else/switch/etc.expression. - TODO
- The unit of indentation is four spaces. No tabs must be used.
- The maximum line length is roughly 120 characters, but readability comes before strict adherence to this rule.
- Switch cases may be indented an additional level.
- TODO
- Use redundant parentheses. Rationale: the order of precedence is sometimes surprising or confusing in Java; using redundant parentheses leaves no room for confusion and prevents errors.
- Write self-documenting code; meaning that identifier names should be informative, logical expressions should be laid out so that they make sense to a human reader, etc. When possible, the code should be written such that it is not necessary to add a comment explaining what it does.
- Don't use
thiswhen not necessary. - TODO
- All public methods and fields, as well as any methods intended to be overridden, must have Javadoc.
- Code comments must be used to explain why code is doing what it is doing, not what it is doing. The what should already be clear from the code itself (see "write self-documenting code" above).
Inside a class, the members go in the following order:
- Constructors
- Instance methods
- Static methods
- Instance fields
- Static fields
- Inner class and interface definitions
Within each category, the scopes should be ordered as follows:
- Public
- Protected
- Package private
- Private
Rationale: the public API of a class is the most relevant for someone reading the source code and should therefore come first. Private methods, as well as fields and other state, are implementation details which should come later.
Code should throw exceptions when something goes wrong. Don't swallow exceptions and don't continue as if nothing happened if a fatal error occurred. The exception should be informative and give relevant context information in the exception message. Use MDCWrappingRuntimeException, MDCCapturingRuntimeException, MDCWrappingException or MDCCapturingException so that the MDC logging context is captured for extra debug information.
Not all existing code adheres to all the style rules for historical reasons. Don't change the formatting of existing code, unless you are changing a significant portion of a file, then you can fix the formatting of the entire file to comply with the rules.
All files should use UTF-8 encoding (without a byte order mark).