Java Coding Conventions
Java Coding Conventions
This document describes a collection of standards, conventions and guidelines for writing Java code that is
easy to understand, to maintain, and to enhance.
Target Audience
Coding standards for Java are important because they lead to greater consistency within code of all
developers. Consistency leads to code that is easier to understand, which in turn results in a code, which is
easier to develop and maintain. Code that is difficult to understand and maintain runs the risk of being
scrapped and rewritten.
A project requirement may vary from the standards mentioned in this document. When going against the
standards, projects should make sure to document it.
1. Naming Convention
Use abbreviations sparingly, but if you do so then use then intelligently and document it
For example, to use a short form for the word “number”, choose one of nbr, no or num.
2. Documentation
Java Comments
Member functions should be named using a full English description, using mixed case with the first letter
of any non-initial word capitalized. The first word of the member function should be a verb.
Examples
openAccount()
printMailingList()
save()
delete()
This results in member functions whose purpose can be determined just by looking at its name.
3.1.1.1 Getters: member functions that return the value of a field / attribute / property of an object.
Use prefix “get” to the name of the field / attribute / property if the field in not boolean
Use prefix “is” to the name of the field / attribute / property if the field is Boolean
A viable alternative is to use the prefix ‘has’ or ‘can’ instead of ‘is’ for boolean getters.
Examples
getFirstName()
isPersistent()
Examples
setFirstName()
3.1.1.3 Constructors: member functions that perform any necessary initialization when an object is created.
Constructors are always given the same name as their class.
Examples
Customer()
SavingsAccount()
A good design requires minimum coupling between the classes. The general rule is to be as restrictive as
possible when setting the visibility of a member function. If member function doesn’t have to be public
then make it protected, and if it doesn’t have to be protected than make it private.
Note: It’s not necessary to document all the factors described above for each and every member function
because not all factors are applicable to every member function.
3.3.3 Document the closing braces If there are many control structures one inside another
4.0 Techniques for Writing Clean Code:
A few blank lines or spaces can help make the code more readable.
Single blank lines to separate logical groups of code, such as control structures
Two blank lines to separate member function definitions
Specify the order of Operations: Use extra parenthesis to increase the readability of the code using AND
and OR comparisons. This facilitates in identifying the exact order of operations in the code
Write short, single command lines Code should do one operation per line So only one statement should
be there per line
Examples
firstName
orderItems
If the name of the field begins with an acronym then the acronym should be completely in lower case
Example
sqlDatabase
Use full English descriptor postfixed by the widget type. This makes it easy for a developer to identify the
purpose of the components as well as its type.
Example
okButton
customerList
fileMenu
newFileMenuItem
5.3 Naming Constants
In Java, constants, values that do not change, are typically implemented as static final fields of classes. The
convention is to use full English words, all in upper case, with underscores between the words
Example
MINIMUM_BALANCE
MAX_VALUE
DEFAULT_START_DATE1
Fields should not be declared public for reasons of encapsulation. All fields should be declared private and
accessor methods should be used to access / modify the field value. This results in less coupling between
classes as the protected / public / package access of field can result in direct access of the field from other
classes
It’s description
Document all applicable invariants Invariants of a field are the conditions that are always true about it.
By documenting the restrictions on the values of a field one can understand important business rules,
making it easier to understand how the code works / how the code is supposed to work
Examples For fields that have complex business rules associated with them one should provide several
example values so as to make them easier to understand
Concurrency issues
Visibility decisions If a field is declared anything but private then it should be documented why it has not
been declared private.
5.6 Usage of Accesors Accessors can be used for more than just getting and setting the values of instance
fields. Accesors should be used for following purpose also:
Initialize the values of fields Use lazy initialization where fields are initialized by their getter member
functions.
Example
/**
* Answer the branch number, which is the leftmost four digits of the full account
* number. Account numbers are in the format BBBBAAAAAA.
*/
protected int getBranchNumber()
{
if(branchNumber == 0)
{
// The default branch number is 1000, which is the
// main branch in downtown Bedrock
setBranchNumber(1000);
}
1
Java Coding Standards
return branchNumber;
}
Note:
This approach is advantageous for objects that have fields that aren’t regularly accessed
Whenever lazy initialization is used in a getter function the programmer should document what is the type
of default value, what the default value as in the example above.
5.6.1 Access constant values Commonly constant values are declared as static final fields. This approach
makes sense for “constants” that are stable.
If the constants can change because of some changes in the business rules as the business matures then it is
better to use getter member functions for constants.
By using accesors for constants programmer can decrease the chance of bugs and at the same time increase
the maintainability of the system.
5.6.2 Access Collections The main purpose of accesors is to encapsulate the access to fields so as to reduce
the coupling within the code. Collections, such as arrays and vectors, being more complex than single value
fields have more than just standard getter and setter member function implemented for them. Because the
business rule may require to add and remove to and from collections, accessor member functions need to be
included to do so.
Example
Member function type Naming Convention Example
Getter for the collection getCollection() getOrderItems()
Setter for the collection setCollection() setOrderItems()
Insert an object into the insertObject() insertOrderItems()
collection
Delete an object from the deleteObject() deleteOrderItems()
collection
Create and add a new object newObject() newOrderItem()
into the collection
Note
The advantage of this approach is that the collection is fully encapsulated, allowing programmer to later
replace it with another structure
It is common to that the getter member functions be public and the setter be protected
Always Initialize Static Fields because one can’t assume that instances of a class will be created before a
static field is accessed
Note
Reusing local variables is more efficient because less memory needs to be allocated, but reusing local
variables decreases the maintainability of code and makes it more fragile
Example
If Account has an attribute called balance and you needed to pass a parameter representing a new value for
it the parameter would be called balance The field would be referred to as this.balance in the code and the
parameter would be referred as balance
Parameters to a member function are documented in the header documentation for the member function
using the javadoc @param tag. It should describe:
What it should be used for
Any restrictions or preconditions
Examples If it is not completely obvious what a parameter should be, then it should provide one or more
examples in the documentation
Note
Use interface as a parameter to the member function then the object itself.
/**
* Classname
*
* Version information
*
* Date
*
* Copyright notice
*/
11.3 Declaration
11.4 Indentation
Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs.
tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).
Note: Examples for use in documentation should have a shorter line length-generally no more than 70
characters.
Following are two examples of indenting method declarations. The first is the conventional case. The
second would shift the second and third lines to the far right if it used conventional indentation, so instead
it indents only 8 spaces.
//CONVENTIONAL INDENTATION
someMethod(int anArg, Object anotherArg, String yetAnotherArg,
Object andStillAnother) {
...
}
Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space)
indentation makes seeing the body difficult. For example:
alpha = (aLongBooleanExpression)
? beta
: gamma;
11.6 Declaration
One declaration per line is recommended since it encourages commenting. In other words,
Note: The examples above use one space between the type and the identifier. Another acceptable
alternative is to use tabs, e.g.:
11.7 Initialization
Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's
declared is if the initial value depends on some computation occurring first.
11.8 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.
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:
Avoid local declarations that hide declarations at higher levels. For example, do not declare the same
variable name in an inner block:
int count;
...
myMethod() {
if (condition) {
int count = 0; // AVOID!
...
}
...
}
When coding Java classes and interfaces, the following formatting rules should be followed:
No space between a method name and the parenthesis "(" starting its parameter list
Open brace "{" appears at the end of the same line as the declaration statement
Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when
it is a null statement the "}" should appear immediately after the "{"
class Sample extends Object {
int ivar1;
int ivar2;
Sample(int i, int j) {
ivar1 = i;
ivar2 = j;
}
int emptyMethod() {}
...
}
11.10 Statements
Simple Statements
Each line should contain at most one statement.
Example:
argv++; // Correct
argc--; // Correct
argv++; argc--; // AVOID!
Compound Statements
Compound statements are statements that contain lists of statements enclosed in braces "{ statements }".
See the following sections for examples.
The enclosed statements should be indented one more level than the compound statement.
The opening brace should be at the end of the line that begins the compound statement; the closing brace
should begin a line and be indented to the beginning of the compound statement.
Braces are used around all statements, even single statements, when they are part of a control structure,
such as a if-else or for statement. This makes it easier to add statements without accidentally introducing
bugs due to forgetting to add braces.
return Statements
A return statement with a value should not use parentheses unless they make the return value more obvious
in some way.
Example:
return;
return myDisk.size();
return (size ? size : defaultSize);
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
Note: if statements always use braces {}. Avoid the following error-prone form:
if (condition) //AVOID! THIS OMITS THE BRACES {}!
statement;
for Statements
An empty for statement (one in which all the work is done in the initialization, condition, and update
clauses) should have the following form:
When using the comma operator in the initialization or update clause of a for statement, avoid the
complexity of using more than three variables. If needed, use separate statements before the for loop (for
the initialization clause) or at the end of the loop (for the update clause).
while Statements
do-while Statements
A do-while statement should have the following form:
do {
statements;
} while (condition);
switch Statements
switch (condition) {
case ABC:
statements;
/* falls through */
case DEF:
statements;
break;
case XYZ:
statements;
break;
default:
statements;
break;
}
Every time a case falls through (doesn't include a break statement), add a comment where the break
statement would normally be. This is shown in the preceding code example with the /* falls through */
comment.
Every switch statement should include a default case. The break in the default case is redundant, but it
prevents a fall-through error if later another case is added.
try-catch Statements
try {
statements;
} catch (ExceptionClass e) {
statements;
}
A try-catch statement may also be followed by finally, which executes regardless of whether or not the try
block has completed successfully.
try {
statements;
} catch (ExceptionClass e) {
statements;
} finally {
statements;
}
Blank Lines
Blank lines improve readability by setting off sections of code that are logically related.
Two blank lines should always be used in the following circumstances:
Between sections of a source file
Between class and interface definitions
Blank Spaces
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.
a += c + d;
a = (a + b) / (c * d);
References:
www.java.sun.com