Java Code Formatting
Code formatting
-
Use four spaces instead of tabs
-
Save your files as UTF-8!
-
Having a blank line between the class declaration and the first variable declaration can help making the class easier to read. However, this is not enforced.
Imports
For (at least) Eclipse, you'll have to set or ensure the following configuration (note: this then will end up a global configuration in your Eclipse IDE):
-
Package import order:
-
java
-
javax
-
org
-
com
-
-
Static package import order: none defined (pushing them under the above defined ones)
-
Number of imports required for .* : 99
-
Number of static imports required for .* : 99
-
Do not create imports for types starting with a lowercase letter: checked
Indentation
The max line length is 120 characters.
If a line exceeds 120 characters, it will need to be wrapped. This can be done according to the following rules:
-
Break after a comma.
-
Break before an operator.
-
Prefer higher-level breaks to lower-level breaks (in other words avoid breaking nested expressions).
-
Indent 8 spaces on the new line.
-
If applied to a method signature, prefer to put each argument below one another.
Examples:
// prefer higher-level breaks longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // for method signatures, put each argument below one another and indent 8 spaces to clearly seperate it from the body someMethod( int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } // indent 8 spaces here, because aligning it makes the logic hard to read. if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); }
Comments
Use javadoc notation in your header comments and comments above functions.
Use a header comment like this:
/** * Brief description of what the code does or where it is used for */
For comments inside functions use the following comment style. Comments come in two forms: block comments (/* */) and line comments (// ). Block comments are rarely used and highly discouraged. Only use them to disable portions of code that should not get executed. Line comments are used to explain the code that follows. They are always on a separate line and above the code it describes. They never trail a piece of code and are never places at the end of a line.
NEVER check in commented-out code. Git will keep the code history for you!
Examples:
public void someMethod() { ... // this is a line comment // even for multiple lines messageService.send(message); /* notifyAdministrator(); logger.info("Sent message to administrator"); */ count++; // DO NOT USE this comment style }
Declarations
Declarations of fields should stick to one on each line. Avoid aligning the field names.
public class Declarations { // correct int number; String text; // DO NOT declare multiple fields in one line int first, second, last; // DO NOT align field names Date expiryDate; List<String> driverNames;
Avoid naming a local variable the same as a higher-level variable (ghosting):
int count; ... myMethod() { if (condition) { int count = 0; ... } ... }
White space
Placing a white space or blank lines largely follows common sense. There are however some points that deserve extra attention.
A keyword followed by a parenthesis should be separated by a space. Example:
while (true) { ... } if (condition) { ... }
Note that a blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls.
Operands and casts should be separated with a white space as well.
(a + b) / (2 - 4) someMethod((int) d);
Using fluent APIs
When working with fluent APIs, when breaking a statement into multiple lines, use a double indent (i.e. 8 spaces), and put the dot at the beginning of the line, such as in the following example:
myFluentObject.performThisOperation() .performAnotherOperation() .performThisToo(someOtherFluentObject.setSomething("foo") .setBarToo(true));
Code blocks
ALWAYS use curly braces for code blocks. This makes the code more readable and avoids bugs. The first curly brace should be on the line of the condition. Example:
while (true) { ... } if (condition) { ... } else if (condition) { ... } else { ... } // DO NOT USE if (condition) if (condition) ... if (condition) ... else if (condition) ... else { ... }
Naming conventions
Identifier type |
Conventions |
Examples |
Packages |
Use only small cap letters, not numbers or dashes. |
java.util |
Classes |
Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). If an acronym is used, then only capitalize the first letter (e.g. HtmlParser instead of HTMLParser) |
Account |
Interfaces |
The same for classes applies to interfaces. Do not use an extra identifier to emphasize it is an interface, like IAccount or AccountInterface |
AccountService |
Methods |
Methods should be verbs or express an active tense, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. Try to avoid very long method names, but do not cut in the expressiveness of the name. |
viewAccount() |
Variables |
All variables are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or other meaningless characters. |
firstName |
Constants |
The exception to variable names are class constants; they should be all uppercase with words separated by underscores ("_"). |
DEFAULT_LOGIN_URL |
Logging
Make extensive and smart usage of logging in debug level. Try to follow logically what the program is doing and log at key points. This is valuable when trying to figure out a problem that occurs in a client environment. There, you may only have access to logs and the logging servlet. By setting the log level to debug, you may be able to pinpoint where things go wrong. Also, it is recommended not to use ERROR level for anything else than unrecoverable errors, or errors that the end user must take action. For all other cases, WARN level should be enough. Last, it is a good practice exposing a stacktrace in debug level, but only an informative message in all other levels. That way a problem does not go unnoticed, but you also prevent the logs from being cluttered with stacktraces.