

[[_TOC_]]
# Java code conventions
## 1 Source file basics
### 1.1 File name
The source file name consists of the case-sensitive name of the top-level class it contains (of which there is [exactly one](#241-Exactly-one-top-level-class-declaration)), plus the `.java` extension.
### 1.2 File encoding: UTF-8
Source files are encoded in **UTF-8**.
### 1.3 Special characters
#### 1.3.1 Whitespace characters
Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that:
1. All other whitespace characters in string and character literals are escaped.
2. Tab characters are not used for indentation.
#### 1.3.2 Special escape sequences
For any character that has a [special escape sequence](https://docs.oracle.com/javase/tutorial/java/data/characters.html) (`\b`, `\t`, `\n`, `\f`, `\r`, `\"`, `\'` and `\\`), that sequence is used rather than the corresponding octal (e.g. `\012`) or Unicode (e.g. `\u000a`) escape.
#### 1.3.3 Non-ASCII characters
For the remaining non-ASCII characters use only non-escaped Unicode characters. Use escaped Unicode characters only for non-printable characters.
**Do not use non-ASCI characters outside string literals and comments.**
## 2. Source file structure
A source file consists of, in order:
1. License and copyright information
2. Package statement
3. Import statements
4. Exactly one top-level class
**Exactly one blank line** separates each section that is present.
Files are not longer than 2000 lines.
### 2.1 License and copyright information
Licence and copyright information must be at the begining of a file.
### 2.2 Package statement
The package statement is **not line-wrapped**. The column limit (Section 3.4, [Column limit: 100](#34-Column-limit-100)) does not apply to package statements.
### 2.3 Import statments
#### 2.3.1 No wildcard imports
**Wildcard imports**, static or otherwise, **are not used**.
#### 2.3.2 No line-wrapping
Import statements are **not line-wrapped**. The column limit (Section 3.4, [Column limit: 100](#34-Column-limit-100)) does not apply to import statements.
#### 2.3.3 Ordering and spacing
Imports are grouped and ordered as follows:
1. All static imports.
2. Same package imports. This group includes imports that have first two package domains same as file.
3. Third party imports. This group includes all imports exept sampe package imports, static imports and standard java imports.
4. Standard java imports. This group includes standard java imports (`java`| `javax`);
If there are multple import groups, a single blank line separates the two blocks. There are no other blank lines between import statements.
Within each block the imported names appear in ASCII sort order. (Note: this is not the same as the import statements being in ASCII sort order, since '.' sorts before ';'.)
#### 2.3.4 No static import for classes
Static import is not used for static nested classes. They are imported with normal imports.
### 2.4 Class declaration
#### 2.4.1 Exactly one top-level class declaration
Each top-level class resides in a source file of its own.
#### 2.4.2 Ordering of class contents
Class content are ordered as follows:
1. Fields
1. Static final fields
2. Static fields
3. Final fields
4. Other fields
2. Static initializer block
3. Constructors
4. Methods
1. Static methods
2. Non-static methods
5. Inner types
1. Static classes
2. Non-static classes
3. Abstract classes
4. Interfaces
5. Enums
Every group above are ordered by accessors as follows:
1. public
2. protected
3. default
4. private
Class contents with same group and accessor are ordered alphabetically.
## 3 Formatting
**Terminology Note**: *block-like construct* refers to the body of a class, method or constructor. Note that, by Section 3.8.3.1 on [array initializers](#3831-Array-initializers-can-be-“block-like”), any array initializer may optionally be treated as if it were a block-like construct.
### 3.1 Braces
#### 3.1.1 Braces are used where optional
Braces are used with `if`, `else`, `for`, `do` and `while` statements, even when the body is empty or contains only a single statement.
#### 3.1.2 Nonempty blocks: K & R style
Braces follow the Kernighan and Ritchie style ("[Egyptian brackets](https://blog.codinghorror.com/new-programming-jargon/)") for nonempty blocks and block-like constructs:
* No line break before the opening brace.
* Line break after the opening brace.
* Line break before the closing brace.
* Line break after the closing brace, only if that brace terminates a statement or terminates the body of a method, constructor, or named class. For example, there is no line break after the brace if it is followed by else or a comma.
Examples:
``` java
return () -> {
while (condition()) {
method();
}
};
return new MyClass() {
@Override public void method() {
if (condition()) {
try {
something();
} catch (ProblemException e) {
recover();
}
} else if (otherCondition()) {
somethingElse();
} else {
lastThing();
}
}
};
```
A few exceptions for enum classes are given in Section 3.8.1, [Enum classes](#381-Enum-classes).
#### 3.1.3 Empty blocks: may be concise
An empty block or block-like construct may be in K & R style (as described in [Section 3.1.2](#312-Nonempty-blocks-K-amp-R-style)). Alternatively, it may be closed immediately after it is opened, with no characters or line break in between ({}), **unless** it is part of a multi-block statement (one that directly contains multiple blocks: `if/else` or `try/catch/finally`).
Examples:
``` java
// This is acceptable
void doNothing() {}
// This is equally acceptable
void doNothingElse() {
}
```
``` java
// This is not acceptable: No concise empty blocks in a multi-block statement
try {
doSomething();
} catch (Exception e) {}
```
### 3.2 Block indentation: 4 spaces
Each time a new block or block-like construct is opened, the indent increases by four spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block. (See the example in Section 3.1.2, [Nonempty blocks: K & R Style](#312-Nonempty-blocks-K-amp-R-style).)
### 3.3 One statement per line
Each statement is followed by a line break.
### 3.4 Column limit: 100
Java code has a column limit of 100 characters. A "character" means any Unicode code point. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in Section 3.5, [Line-wrapping](#35-Line-wrapping).
>Each Unicode code point counts as one character, even if its display width is greater or less. For example, if using [fullwidth characters](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms), you may choose to wrap the line earlier than where this rule strictly requires.
**Exceptions:**
1. Lines where obeying the column limit is not possible (for example, a long URL in Javadoc, or a long JSNI method reference).
2. `package` and `import` statements (see Sections 2.2 [Package statement](#22-Package-statement) and 2.3 [Import statements](#23-Import-statements)).
3. Command lines in a comment that may be cut-and-pasted into a shell.
### 3.5 Line-wrapping
**Terminology Note:** When code that might otherwise legally occupy a single line is divided into multiple lines, this activity is called line-wrapping.
There is no comprehensive, deterministic formula showing exactly how to line-wrap in every situation. Very often there are several valid ways to line-wrap the same piece of code.
>**Note**: While the typical reason for line-wrapping is to avoid overflowing the column limit, even code that would in fact fit within the column limit may be line-wrapped at the author's discretion.
#### 3.5.1 Where to break
The prime directive of line-wrapping is: prefer to break at a **higher syntactic level**. Also:
1. When a line is broken at a non-assignment operator the break comes before the symbol.
* This also applies to the following "operator-like" symbols:
* the dot separator (.)
* the two colons of a method reference (::)
* an ampersand in a type bound (```<T extends Foo & Bar>```)
* a pipe in a catch block (catch (```FooException | BarException e```)).
1. When a line is broken at an assignment operator the break typically comes after the symbol, but either way is acceptable.
* This also applies to the "assignment-operator-like" colon in an enhanced `for` ("foreach") statement.
1. A method or constructor name stays attached to the open parenthesis (`(`) that follows it.
1. A comma (`,`) stays attached to the token that precedes it.
1. A line is never broken adjacent to the arrow in a lambda, except that a break may come immediately after the arrow if the body of the lambda consists of a single unbraced expression. Examples:
``` java
MyLambda<String, Long, Object> lambda =
(String label, Long value, Object obj) -> {
...
};
Predicate<String> predicate = str ->
longExpressionInvolving(str);
```
> **Note**: The primary goal for line wrapping is to have clear code, not necessarily code that fits in the smallest number of lines.
#### 3.5.2 Indent continuation lines at 4 spaces
When line-wrapping, each line after the first (each continuation line) is indented at 4 spaces from the original line.
### 3.6 Whitespace
#### 3.6.1 Vertical Whitespace
A single blank line always appears:
1. Between consecutive members or initializers of a class: fields, constructors, methods, nested classes, static initializers, and instance initializers.
* **Exception**: Blank lines between enum constants are covered in [Section 3.8.1](#381-Enum-classes).
1. As required by other sections of this document (such as Section 2, [Source file structure](#2-Source-file-structure), and Section 2.3, [Import statements](#23-Import-statements)).
A single blank line may also appear anywhere it improves readability, for example between statements to organize the code into logical subsections. A blank line before the first member or initializer, or after the last member or initializer of the class, is neither encouraged nor discouraged.
Multiple consecutive blank lines are not permitted.
#### 3.6.2 Horizontal whitespace
Beyond where required by the language or other style rules, and apart from literals, comments and Javadoc, a single ASCII space also appears in the following places only.
1. Separating any reserved word, such as `if`, `for` or `catch`, from an open parenthesis (`(``) that follows it on that line
1. Separating any reserved word, such as `else` or `catch`, from a closing curly brace (`}`) that precedes it on that line
1. Before any open curly brace (`{`), with two exceptions:
* ```@SomeAnnotation({a, b})``` (no space is used)
* ```String[][] x = {{"foo"}};``` (no space is required between `{{`, by item 8 below)
1. On both sides of any binary or ternary operator. This also applies to the following "operator-like" symbols:
* the ampersand in a conjunctive type bound: ```<T extends Foo & Bar>```
* the pipe for a catch block that handles multiple exceptions: ```catch (FooException | BarException e)```
* the colon (`:`) in an enhanced `for` ("foreach") statement
* the arrow in a lambda expression: ```(String str) -> str.length()```
but not
* the two colons (`::`) of a method reference, which is written like ```Object::toString```
* the dot separator (`.``), which is written like ```object.toString()```
1. After `,:;` or the closing parenthesis (`)`) of a cast
1. On both sides of the double slash (`//`) that begins an end-of-line comment. Here, multiple spaces are allowed, but not required.
1. Between the type and variable of a declaration: ```List<String> list```
1. Optional just inside both braces of an array initializer
* ```new int[] {5, 6}``` and ```new int[] { 5, 6 }``` are both valid
1. Between a type annotation and `[]` or `...`
This rule is never interpreted as requiring or forbidding additional space at the start or end of a line; it addresses only interior space.
#### 3.6.3 Horizontal alignment: never
**Terminology Note:** Horizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines.
Horizontal aligment is forbidden.
Example:
``` java
private int x; // this is fine
private Color color; // this too
// not fine
private int x;
private Color color;
```
### 3.7 Grouping parentheses: recommended
Optional grouping parentheses are omitted only when author and reviewer agree that there is no reasonable chance the code will be misinterpreted without them, nor would they have made the code easier to read.
### 3.8 Specific constructs
#### 3.8.1 Enum classes
After each comma that follows an enum constant, a line break is optional. Additional blank lines (usually just one) are also allowed. This is one possibility:
``` java
private enum Answer {
YES {
@Override public String toString() {
return "yes";
}
},
NO,
MAYBE
}
```
An enum class with no methods and no documentation on its constants may optionally be formatted as if it were an array initializer (see Section 3.8.3.1 on [array initializers](#3831-Array-initializers-can-be-“block-like”)).
``` java
private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS }
```
Since enum classes are classes, all other rules for formatting classes apply.
#### 3.8.2 Variable declarations
##### 3.8.2.1 One variable per declaration
Every variable declaration (field or local) declares only one variable: declarations such as ```int a, b;``` are not used.
**Exception:** Multiple variable declarations are acceptable in the header of a for loop.
##### 3.8.2.2 Declared when needed
Local variables are **not** habitually declared at the start of their containing block or block-like construct. Instead, local variables are declared close to the point they are first used (within reason), to minimize their scope. Local variable declarations typically have initializers, or are initialized immediately after declaration.
##### 3.8.2.3 Placement
Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces `{` and `}`.) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.
```java
void myMethod() {
int int1 = 0; // beginning of method block
if (condition) {
int int2 = 0; // beginning of "if" block
...
}
}
```
The one exception to the rule is indexes of `for` loops, which in Java can be declared in the `for` statement:
```java
for (int i = 0; i < maxLoops; i++) { ... }
```
Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:
``` java
int count;
...
myMethod() {
if (condition) {
int count = 0; // AVOID!
...
}
...
}
```
#### 3.8.3 Arrays
##### 3.8.3.1 Array initializers: can be "block-like"
Any array initializer may optionally be formatted as if it were a "block-like construct." For example, the following are all valid (not an exhaustive list):
``` java
new int[] { new int[] {
0, 1, 2, 3 0,
} 1,
2,
new int[] { 3,
0, 1, }
2, 3
} new int[]
{0, 1, 2, 3}
```
##### 3.8.3.2 No C-style array declarations
The square brackets form a part of the type, not the variable: ```String[] args```, not ```String args[]```.
#### 3.8.4 Switch statements
**Terminology Note:** Inside the braces of a switch block are one or more statement groups. Each statement group consists of one or more switch labels (either `case FOO:` or `default:`), followed by one or more statements (or, for the last statement group, zero or more statements).
##### 3.8.4.1 Indentation
As with any other block, the contents of a switch block are indented with 4 spaces.
After a switch label, there is a line break, and the indentation level is increased for 4 spaces, exactly as if a block were being opened. The following switch label returns to the previous indentation level, as if a block had been closed.
##### 3.8.4.2 Fall-through: commented
Within a switch block, each statement group either terminates abruptly (with a `break`, `continue`, `return` or thrown exception), or is marked with a comment to indicate that execution will or might continue into the next statement group. Any comment that communicates the idea of fall-through is sufficient (typically `// fall through`). This special comment is not required in the last statement group of the switch block. Example:
```java
switch (input) {
case 1:
case 2:
prepareOneOrTwo();
// fall through
case 3:
handleOneTwoOrThree();
break;
default:
handleLargeNumber(input);
}
```
Notice that no comment is needed after `case 1:`, only at the end of the statement group.
##### 3.8.4.3 The `default` case is present
Each switch statement includes a `default` statement group, even if it contains no code.
**Exception:** A switch statement for an enum type may omit the default statement group, if it includes explicit cases covering all possible values of that type. This enables IDEs or other static analysis tools to issue a warning if any cases were missed.
#### 3.8.5 Annotations
Annotations applying to a class, method or constructor appear immediately after the documentation block, and each annotation is listed on a line of its own (that is, one annotation per line). These line breaks do not constitute line-wrapping (Section 3.5, [Line-wrapping](#35-Line-wrapping)), so the indentation level is not increased. Example:
``` java
@Override
@Nullable
public String getNameIfPresent() { ... }
```
Annotations applying to a field also appear immediately after the documentation block, but in this case, multiple annotations (possibly parameterized) may be listed on the same line; for example:
``` java
@Partial @Mock DataLoader loader;
```
There are no specific rules for formatting annotations on parameters, local variables, or types.
#### 3.8.6 Comments
Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are those found in C++, which are delimited by `/*...*/`, and `//`. Documentation comments (known as "doc comments") are Java-only, and are delimited by `/**...*/`.
This section addresses implementation comments. Javadoc is addressed separately in Section 6, [Javadoc](#6-Javadoc).
Implementation comments are mean for commenting out code or for comments about the particular implementation. Doc comments are meant to describe the specification of the code, from an implementation-free perspective. to be read by developers who might not necessarily have the source code at hand.
Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.
Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves.
> **Note:** The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.
Comments should not be enclosed in large boxes drawn with asterisks or other characters.
Comments should never include special characters such as form-feed and backspace.
##### 3.8.6.1 Block comments
Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments may be used at the beginning of each file and before each method. They can also be used in other places, such as within methods. Block comments inside a function or method should be indented to the same level as the code they describe.
A block comment should be preceded by a blank line to set it apart from the rest of the code.
``` java
/*
* Here is a block comment.
*/
```
##### 3.8.6.2 Single-line comments
Short comments can appear on a single line indented to the level of the code that follows. If a comment can't be written in a single line, it should follow the block comment format (see section 5.1.1). A single-line comment should be preceded by a blank line.
```java
if (condition) {
/* Handle the condition. */
...
}
```
##### 3.8.6.3 Trailing Comments
Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting.
```java
if (a == 2) {
return TRUE; /* special case */
} else {
return isPrime(a); /* works only for odd a */
}
```
##### 3.8.6.4 End-Of-Line Comments
The `//` comment delimiter can comment out a complete line or only a partial line. It shouldn't be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow:
```java
if (foo > 1) {
// Do a double-flip.
...
}
else {
return false; // Explain why here.
}
//if (bar > 1) {
//
// // Do a triple-flip.
// ...
//}
//else {
// return false;
//}
```
#### 3.8.7 Modifiers
Class and member modifiers, when present, appear in the order recommended by the Java Language Specification:
```
public protected private abstract default static final transient volatile synchronized native strictfp
```
#### 3.8.8 Numeric Literals
`long`-valued integer literals use an uppercase `L` suffix, never lowercase (to avoid confusion with the digit `1`). For example, `3000000000L` rather than `3000000000l`. Because of consistency, this also apply to `float` and `double` literals. Use `F` instead of `f` and `D` instead of `d`.
## 4 Naming
### 4.1 Rules common to all identifiers
Identifiers use only ASCII letters and digits, and, in a small number of cases noted below, underscores. Thus each valid identifier name is matched by the regular expression \w+ .
### 4.2 Rules by identifier type
#### 4.2.1 Package names
Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example, `com.example.deepspace`, not `com.example.deepSpace` or `com.example.deep_space`.
#### 4.2.2 Class names
Class names are written in [UpperCamelCase](#43-Camel-case-defined).
Class names are typically nouns or noun phrases. For example, `Character` or `ImmutableList`. Interface names may also be nouns or noun phrases (for example, `List`), but may sometimes be adjectives or adjective phrases instead (for example, `Readable`).
Test classes are named starting with the name of the class they are testing, and ending with Test. For example, HashTest or HashIntegrationTest.
#### 4.2.3 Method names
Method names are written in [lowerCamelCase](#43-Camel-case-defined).
Method names are typically verbs or verb phrases. For example, `sendMessage` or `stop`.
For unit test methods `Test` suffix should be added. For example, `sendMessageTest` or `stopTest`.
#### 4.2.4 Constant names
Constant names use **CONSTANT_CASE:** all uppercase letters, with each word separated from the next by a single underscore. But what is a constant, exactly?
Constants are static final fields whose contents are deeply immutable and whose methods have no detectable side effects. This includes primitives, Strings, immutable types, and immutable collections of immutable types. If any of the instance's observable state can change, it is not a constant. Merely intending to never mutate the object is not enough. Examples:
``` java
// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final ImmutableMap<String, Integer> AGES = ImmutableMap.of("Ed", 35, "Ann", 32);
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }
// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final ImmutableMap<String, SomeMutableType> mutableValues =
ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};
```
These names are typically nouns or noun phrases.
#### 4.2.5 Non-constant field names
Non-constant field names (static or otherwise) are written in [lowerCamelCase](#43-Camel-case-defined).
These names are typically nouns or noun phrases. For example, `computedValues` or `index`.
#### 4.2.6 Parameter names
Parameter names are written in [lowerCamelCase](#43-Camel-case-defined).
One-character parameter names in public methods are not allowed.
#### 4.2.7 Local variable names
Local variable names are written in [lowerCamelCase](#43-Camel-case-defined).
Even when final and immutable, local variables are not considered to be constants, and should not be styled as constants.
#### 4.2.8 Type variable names
Each type variable is named as a single capital letter, optionally followed by a single numeral (such as `E`, `T`, `X`, `T2`)
### 4.3 Camel case: defined
Beginning with the prose form of the name:
1. Convert the phrase to plain ASCII and remove any apostrophes. For example, "Müller's algorithm" might become "Muellers algorithm".
1. Divide this result into words, splitting on spaces and any remaining punctuation (typically hyphens).
* **Recommended:** if any word already has a conventional camel-case appearance in common usage, split this into its constituent parts (e.g., "AdWords" becomes "ad words"). Note that a word such as "iOS" is not really in camel case per se; it defies any convention, so this recommendation does not apply.
1. Now lowercase everything (including acronyms), then uppercase only the first character of:
* ... each word, to yield upper camel case, or
* ... each word except the first, to yield lower camel case
1. Finally, join all the words into a single identifier.
Note that the casing of the original words is almost entirely disregarded. Examples:
| Prose from | Correct | Incorrect |
| ---------------------- | ----------------- | ------------------------ |
| "XML HTTP request" | XmlHttpRequest | XMLHTTPRequest |
| "new customer ID" | newCustomerId | newCustomerID |
| "inner stopwatch" | innerStopwatch | innerStopWatch |
| "supports IPv6 on iOS?" | supportsIpv6OnIos | supportsIPv6OnIOS |
|"YouTube importer" | YouTubeImporter |
## 5 Programming Practices
### 5.1 `@Override`: always used
A method is marked with the `@Override` annotation whenever it is legal. This includes a class method overriding a superclass method, a class method implementing an interface method, and an interface method respecifying a superinterface method.
### 5.2 Caught exceptions: not ignored
Except as noted below, it is very rarely correct to do nothing in response to a caught exception. (Typical responses are to log it, or if it is considered "impossible", rethrow it as an `AssertionError`.)
When it truly is appropriate to take no action whatsoever in a catch block, the reason this is justified is explained in a comment.
``` java
try {
int i = Integer.parseInt(response);
return handleNumericResponse(i);
} catch (NumberFormatException ok) {
// it's not numeric; that's fine, just continue
}
return handleTextResponse(response);
```
**Exception:** In tests, a caught exception may be ignored without comment if its name is or begins with expected. The following is a very common idiom for ensuring that the code under test does throw an exception of the expected type, so a comment is unnecessary here.
```java
try {
emptyStack.pop();
fail();
} catch (NoSuchElementException expected) {
}
```
### 5.3 Static members: qualified using class
When a reference to a static class member must be qualified, it is qualified with that class's name, not with a reference or expression of that class's type.
``` java
Foo aFoo = ...;
Foo.aStaticMethod(); // good
aFoo.aStaticMethod(); // bad
somethingThatYieldsAFoo().aStaticMethod(); // very bad
```
### 5.4 Finalizers: not used
Do not override `Object.finalize`.
### 5.5 Numeric constants
Numerical constants (literals) should not be coded directly, except for `-1`, `0`, and `1`, which can appear in a for loop as counter values.
### 5.6 Variable Assignments
Avoid assigning several variables to the same value in a single statement. It is hard to read. Example:
```java
fooBar.fChar = barFoo.lchar = 'c'; // AVOID!
```
Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example:
```java
if (c++ = d++) { // AVOID! (Java disallows)
...
}
```
should be written as
```java
if ((c++ = d++) != 0) {
...
}
```
Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example:
```java
d = (a = b + c) + r; // AVOID!
```
should be written as
```java
a = b + c;
d = a + r;
```
### 5.6 Miscellaneous Practices
#### 5.6.1 Parentheses
It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others-you shouldn't assume that other programmers know precedence as well as you do.
```java
if (a == b && c == d) // AVOID!
if ((a == b) && (c == d)) // RIGHT
```
#### 5.6.2 Returning Values
Try to make the structure of your program match the intent. Example:
```java
if (booleanExpression) {
return true;
} else {
return false;
}
```
should instead be written as
```java
return booleanExpression;
```
Similarly,
```java
if (condition) {
return x;
}
return y;
```
should be written as
```java
return (condition ? x : y);
```
#### 5.6.3 Expressions before `?` in the Conditional Operator
If an expression containing a binary operator appears before the `?` in the ternary `?:` operator, it should be parenthesized. Example:
```java
(x >= 0) ? x : -x;
```
#### 5.6.4 Special Comments
Use `XXX` in a comment to flag something that is bogus but works. Use `FIXME` to flag something that is bogus and broken.
## 6 Javadoc
See [Javadoc conventions](https://gitlab.com/icp-ts/icpweb/middleware/wikis/code-conventions/Javadoc-Conventions).
## 7 Spring framwork
### 7.1 Spring MVC
#### 7.1.1 `@RequestMapping` methods should be `public`
A method with a `@RequestMapping` annotation part of a class annotated with `@Controller` (directly or indirectly through a meta annotation - `@RestController` from Spring Boot is a good example) will be called to handle matching web requests. That will happen even if the method is private, because Spring invokes such methods via reflection, without checking visibility.
So marking a sensitive method `private` may seem like a good way to control how such code is called. Unfortunately, not all Spring frameworks ignore visibility in this way. For instance, if you've tried to control web access to your sensitive, `private`, `@RequestMapping` method by marking it `@Secured` ... it will still be called, whether or not the user is authorized to access it. That's because AOP proxies are not applied to non-public methods.
In addition to `@RequestMapping`, this rule also considers the annotations introduced in Spring Framework 4.3: `@GetMapping`, `@PostMapping`, `@PutMapping`, `@DeleteMapping`, `@PatchMapping`.
#### 7.1.2 Use composed `@RequestMapping` variants
Spring framework 4.3 introduced variants of the `@RequestMapping` annotation to better represent the semantics of the annotated methods. The use of `@GetMapping`, `@PostMapping`, `@PutMapping`, `@PatchMapping` and `@DeleteMapping` should be preferred to the use of the raw `@RequestMapping(method = RequestMethod.XYZ)`.
### 7.2 Configuration
#### 7.2.1 `@EnableAutoConfiguration` should be fine-tuned
`@EnableAutoConfiguration` is a convenient feature to configure the Spring Application Context by attempting to guess the beans that you are likely to need. The drawback is that it may load and configure beans the application will never use and therefore consume more CPU and RAM than really required. `@EnableAutoConfiguration` should be configured to exclude all the beans not required by the application. Alternatively, use the `@Import` annotation instead of `@EnableAutoConfiguration`, to explicitly import the useful AutoConfiguration classes.
This rule applies for `@SpringBootApplication` as well.
Noncompliant Code Example:
``` java
@SpringBootApplication
public class MyApplication {
...
}
```
``` java
@Configuration
@EnableAutoConfiguration
public class MyApplication {
...
}
```
Compliant Code Example:
``` java
@SpringBootApplication(exclude = {
MultipartAutoConfiguration.class,
JmxAutoConfiguration.class,
})
public class MyApplication {
...
}
```
``` java
@Configuration
@EnableAutoConfiguration(exclude = {
MultipartAutoConfiguration.class,
JmxAutoConfiguration.class,
})
public class MyApplication {
...
}
```
``` java
@Configuration
@Import({
DispatcherServletAutoConfiguration.class,
EmbeddedServletContainerAutoConfiguration.class,
ErrorMvcAutoConfiguration.class,
HttpEncodingAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
JacksonAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
ThymeleafAutoConfiguration.class,
WebMvcAutoConfiguration.class
})
public class MyApplication {
...
}
```
#### 7.2.2 `@Import` should be preferred to `@ComponentScan`
`@ComponentScan` is used to find which Spring `@Component` beans (`@Service` or `@Repository` or `@Controller`) are available in the classpath so they can be used in the application context. This is a convenient feature especially when you begin a new project but it comes with the drawback of slowing down the application start-up time especially when the application becomes bigger (ie: it references a large JAR file, or it references a significant number of JAR files, or the base-package refers to a large amount of .class files).
`@ComponentScan` should be replaced by an explicit list of Spring beans loaded by `@Import`.
The interface `@SpringBootApplication` is also considered by this rule because it is annotated with `@ComponentScan`.
Noncompliant Code Example:
``` java
@ComponentScan
public class MyApplication {
...
}
@SpringBootApplication
public class MyApplication {
...
}
```
Compliant Code Example:
```java
@Configuration
@Import({
DispatcherServletAutoConfiguration.class,
ErrorMvcAutoConfiguration.class,
HttpEncodingAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
MultipartAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class,
WebMvcAutoConfiguration.class
})
public class MyApplication {
...
}
```
### 7.3 Injection
#### 7.3.1 Spring components should use constructor injection
Spring `@Component`, `@Controller`, `@Service`, and `@Repository` classes are singletons by default, meaning only one instance of the class is ever instantiated in the application. Typically such a class might have a few `static` members, such as a logger, but all non-static members should be managed by Spring and supplied via constructor injection rather than by field injection.
#### 7.3.2 Factory method injection should be used in `@Configuration` classes
When `@Autowired` is used, dependencies need to be resolved when the class is instantiated, which may cause early initialization of beans or lead the context to look in places it shouldn't to find the bean. To avoid this tricky issue and optimize the way the context loads, dependencies should be requested as late as possible. That means using parameter injection instead of field injection for dependencies that are only used in a single `@Bean` method.
Noncompliant Code Example:
``` java
@Configuration
public class FooConfiguration {
@Autowired private DataSource dataSource; // Noncompliant
@Bean
public MyService myService() {
return new MyService(this.dataSource);
}
}
```
Compliant Code Example:
```java
@Configuration
public class FooConfiguration {
@Bean
public MyService myService(DataSource dataSource) {
return new MyService(dataSource);
}
}
```
#### 7.3.3 Members of Spring components should be injected
Spring `@Component`, `@Controller`, `@Service`, and `@Repository` classes are singletons by default, meaning only one instance of the class is ever instantiated in the application. Typically such a class might have a few `static` members, such as a logger, but all non-static members should be managed by Spring. That is, they should have one of these annotations: `@Resource`, `@Inject`, `@Autowired` or `@Value`.
Having non-injected members in one of these classes could indicate an attempt to manage state. Because they are singletons, such an attempt is almost guaranteed to eventually expose data from User1's session to User2.