Java Coding Standards


Why Have Code Conventions
Code conventions are important to programmers for a number of reasons:
80% of the lifetime cost of a piece of software goes to maintenance.
Hardly any software is maintained for its whole life by the original author.
Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.

General Principles
Use full English descriptors that accurately describe the variable/field/class/…
For example, use names like firstName, grandTotal,or CorporateCustomer. Although names like x1, y1,or fn are easy to type because they’re short, they don’t provide any indication of what they represent and result in code that is difficult to understand, maintain, and enhance.

Use mixed case to make names readable You should use lower case letters in general, but capitalize the first letter of class names and interface names, as well as the first letter of any non-initial word.

Use short forms sparingly, but if you do so then use them intelligently. Use of standard abbreviations is acceptable. Acronyms should be in block capitals (e.g. NATO, ISO, SWIFT).

Avoid long names (< 15 characters is a good idea). Although the class name PhysicalOrVirtualProductOrService might seem to be a good class name at the time, this name is simply too long and you should consider renaming it to something shorter, perhaps something like Offering.

Avoid names that are similar or differ only in case. For example, the variable names persistentObject and persistentobject should not be used together, nor should anSqlDatabase and anSQLDatabase.

No leading or trailing underscores. Names with leading or trailing underscores are reserved for system purposes, and may not be used for any user-created names except for pre-processor defines More importantly, underscores are annoying and difficult to type so I try to avoid their use whenever possible.

Business-relevant. All names should be business-like. Strictly no attempts at humour, references to pop culture (music, films, TV – especially Star Trek).

Comments

Comments should add to the clarity of your code. The reason why you document your
code is to make it more understandable to you, your coworkers, and to any other developer who comes after you.

If your code isn’t worth documenting, it probably isn’t worth running. This includes your code for tests – especially if it will be used for regression testing.

Avoid decoration, i.e. don’t use banner-like comments. Write clean, businesslike code, not pretty code

Keep comments simple. Simple, point-form notes. Don’t write a book, just provide enough information so that others can understand your code.

Write the documentation before you write the code. The best way to document code is to write the comments before you write the code. This gives you an opportunity to think about how the code will work before you write it and will ensure that the documentation gets written. If the business logic changes then change the comments first. If there is a difference between the comments and the code then the code must be wrong.

No apologies. Do not apologise for the code or the lack of comments. This might not inspire confidence in a customer. Document the problem and circulate it within the team.

Document why something is being done, not what. Any programmer can always look at a piece of code and figure out what it does. For example, you can look at the code in Example below and figure out that a 5% discount is being given on orders of $1,000 or more. Why is this being done? Is there a business rule that says that large orders get a discount? Is there a limited-time special on large orders or is it a permanent program? Was the original programmer just being generous? You don’t know unless it’s documented somewhere, either in the source code itself or in an external document.

Example: Code without comments loses
Business Logic
if ( grandTotal >= 1000.00) { grandTotal = grandTotal * 0.95; }

File Names

This section lists commonly used file suffixes and names.
File Suffixes Java Software uses the following file suffixes:
File Type Suffix
Java source .java
Java bytecode .class
Java Archive File .jar

2. Common File Names File Type Suffix Java source .java Java bytecode .class Java Archive File .jar

Frequently used file names include:
File Name       Use
GNUmakefile The preferred name for makefiles. We use gnumake to build our
software.
README      The preferred name for the file that summarizes the contents of a
particular directory.

File Organization
A file consists of sections that should be separated by blank lines and an optional comment identifying each section.
Files longer than 2000 lines are cumbersome and should be avoided.
For an example of a Java program properly formatted, see Java Source File Example

Java Source Files
Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class should be the first class or interface in the file. Java source files have the following ordering:
Beginning comments
Package and Import statements
Class and interface declarations

Beginning Comments All source files should begin with a c-style comment that lists the
class name, version information, date, and copyright notice:
/* * Classname            *
* Version information *
* Date                          *
* Copyright notice      *
*/

Package and Import Statements
The first non-comment line of most Java source files is a package statement. After that, import statements can follow. For example: package java.awt; import java.awt.peer.CanvasPeer; Note: The first component of a unique package name is always written in alllowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.

Class and Interface Declarations
The following table describes the parts of a class or interface declaration, in the order that they should appear. See Java Source File Example for an example that includes comments.

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).

Line Length
Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools. Note: Examples for use in documentation should have a shorter line lengthgenerally no more than 70 characters.

Wrapping Lines
When an expression will not fit on a single line, break it according to these general principles:
Break after a comma.
Break before an operator.
Prefer higher-level breaks to lower-level breaks.
Align the new line with the beginning of the expression at the same level on the previous line. I
f the above rules lead to confusing code or to code that's squished up against the right margin, just indent 8 spaces instead. Here are some examples of breaking method calls: someMethod(longExpression1, longExpression2, longExpression3, longExpression4, longExpression5);
var = someMethod1(longExpression1, someMethod2(longExpression2, longExpression3)); Following are two examples of breaking an arithmetic expression.
The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6;
// PREFERED
longName1 = longName2 * (longName3 + longName4 o longName5) + 4 * longname6;
// AVOID
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

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 /**...*/. Doc comments can be extracted to HTML files using the javadoc tool. 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 non-obvious 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, and should never include special characters such as form-feed and backspace.

Implementation Comment Formats
Programs can have four styles of implementation comments: block, single-line, trailing, and end-of-line.
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.
/* * Here is a block comment. */
Block comments can start with
/*-, which is recognized by indent(1) as the beginning of a block comment that should not be reformatted. Example:
/*- * Here is a block comment with some very special *
formatting that I want indent(1) to ignore. *
* one
* two
* three
*/

Note: If you don't use indent(1), you don't have to use
/*- in your code or make any other concessions to the possibility that someone else might run indent(1) on your code.

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. A single-line comment should be preceded by a blank line. Here's an example of a single-line comment in Java code :

if (condition) {
 /* Handle the condition. */
 ... }

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.
Here's an example of a trailing comment in Java code:
if (a == 2) {
return TRUE; /* special case */
} else {
return isPrime(a); /* works only for odd a */
}

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:
if (foo > 1) {
// Do a double-flip. ...
} else { return false; // Explain why here. }
//if (bar > 1) {
//
//
// Do a triple-flip.
// ...
//}
//else {
// return false;
//}

Declarations
Number Per Line

One declaration per line is recommended since it encourages commenting. In other words,
int level; // indentation level
int size; // size of table is preferred over
int level, size;
Do not put different types on the same line.
Example:
int foo, fooarray[]; //WRONG!
Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e.g.: int level; // indentation level
int size; // size of table
Object currentEntry; // currently selected table entry

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.

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:
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:
int count;
...
myMethod() {
if (condition) {
int count = 0; // AVOID!
...
}
...
}

Class and Interface Declarations

When coding Java classes and interfaces, the following formatting rules should be followed:
Each method and class should start from the left margin
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 "{"
An example of a class :
class Sample extends Object {
int ivar1;
 int ivar2;
Sample(int i, int j) {
ivar1 = i;
ivar2 = j;
}
int emptyMethod() {}
...
}
Methods are separated by a blank line


Naming Accessor Methods
The naming conventions for accessors, however, are summarized below.
1. Get Methods
Get methods that return the value of an attribute. You should prefix the word
‘get’ to the name of the attribute, unless it is returning a boolean when you
should prefix ‘is’ to the name of the attribute instead of ‘get.’
Examples:
getFirstName()
getAccountNumber()
isPersistent()
isAtEnd()
By following this naming convention you make it obvious that a method
returns an attribute of an object, and for boolean getters you make it obvious
that it returns true or false. Another advantage of this standard is that it
follows the naming conventions used by the beans development kit (BDK) for
get methods.

2. Set Methods
Set methods modify the values of an attribute. You should prefix the word
‘set’ to the name of
the attribute, regardless of the attribute type.
Examples:
setFirstName(String aName)
setAccountNumber(int anAccountNumber)
setReasonableGoals(Vector newGoals)
setPersistent(boolean isPersistent)
setAtEnd(boolean isAtEnd)
Following this naming convention you make it obvious that a method sets the
value of an attribute of an object.

3. Method Visibility
For a good design where you minimize the coupling between classes, the
general rule of thumb is to be as restrictive as possible when setting the
visibility of a method. If method doesn’t have to be public then make it
protected, and if it doesn’t have to be protected then make it private.

By default, your non-public methods should be protected unless you are sure that you wish to deny them to sub-classes.

Public A public method can be invoked by any other method in any othe
object or class. When the method must be accessible by objects
and classes outside of the class hierarchy in which the method is
defined.
Protected A protected method can be invoked by any method in the class i
which it is defined or any subclasses of that class. When the
method provides behavior that is needed internally within the cla
hierarchy but not externally.
Private A private method can only be invoked by other methods in the
class in which it is defined, but not in the subclasses When the
method provides behavior that is specific to the class. Private
methods are often the result of refactoring, also known as
reorganizing, the behavior of other methods within the class to
encapsulate one specific behavior

Documenting Methods
The manner in which you document a method will often be the deciding factor as to whether or not it is understandable, and therefore maintainable and extensible. You should pay particular attention to both public and protected methods as they are accessible to clients of the class. Private methods other than simple accessors should be documented as they are usually where the interesting design decisions are implemented.

The Method Header
Every Java method should include some sort of header, called method documentation, at the top of the source code that documents all of the information that is critical to understanding it. This information includes, but is not limited to the following:

What and why the method does what it does.
By documenting what a method does you make it easier for others to determine if they can reuse
your code. Documenting why it does something makes it easier for others to put your code into
context. You also make it easier for others to determine whether or not a new change should
actually be made to a piece of code (perhaps the reason for the new change conflicts with the
reason why the code was written in the first place).
What a method must be passed as parameters.
You also need to indicate what parameters, if any, must be passed to a method, how they will be
used, and what type of class they are an instance of. This information is needed so that other
programmers know what information to pass to a method. The javadoc @param tag is used for
this.
Public A public method can be invoked by any other method in any othe
object or class. When the method must be accessible by objects
and classes outside of the class hierarchy in which the method is
defined.
Protected A protected method can be invoked by any method in the class i
which it is defined or any subclasses of that class. When the
method provides behavior that is needed internally within the cla
hierarchy but not externally.
Private A private method can only be invoked by other methods in the
class in which it is defined, but not in the subclasses When the
method provides behavior that is specific to the class. Private
methods are often the result of refactoring, also known as
reorganizing, the behavior of other methods within the class to
encapsulate one specific behavior.

What a method returns.
You need to document what, if anything, a method returns so that other programmers can use the
return value/object appropriately. The javadoc @return tag is used for this.
Known bugs.
Any outstanding problems with a method should be documented so that other developers
understand the weaknesses/difficulties with the method. If a given bug is applicable to more than
one method within a class, then it should be documented for the class instead.
Any exceptions that a method throws.
You should document any and all exceptions that a method throws so that other programmers
know what their code will need to catch. The javadoc @exception tag is used for this.
Visibility decisions.
If you feel that your choice of visibility for a method will be questioned by other developers,
perhaps you’ve made a method public even though no other objects invoke the method yet, then
you should document your decision. This will help to make your thinking clear to other developers
so that they don’t waste time worrying about why you did something questionable.
How a method changes the object.
If a method changes an object, for example the withdraw() method of a bank account modifies the
account balance then this needs to be indicated. This information is needed so that other Java
programmers know exactly how a method invocation will affect the target object.
Examples of how to invoke the method if appropriate.
One of the easiest ways to determine how a piece of code works it to look at an example. Consider
including an example or two of how to invoke a method. N.B. Public & Protected methods only.
Applicable pre-conditions and post-conditions.
A precondition is a constraint under which a method will function properly, and a post-condition is a
property or assertion that will be true after a method is finished running. In many ways preconditions
and post-conditions describe the assumptions that you have made when writing a
method, defining exactly the boundaries of how a method is used.
All concurrency issues.
Concurrency is a new and complex concept for many developers and at best it’s an old and
complex topic for experienced concurrent programmers. The end result is that if you use the
concurrent programming features of Java then you need to document it thoroughly. When a class
includes both synchronized and unsynchronized methods you must document the execution context
that a method relies on, especially when it requires unrestricted access so that other developers
can use your methods safely. When a setter, a method that updates an attribute, of a class that
implements the runnable interface is not synchronized then you should document your reason(s)
why.
Finally, if you override or overload a method and change its synchronization you should also
document why. The important thing is that you should document something only when it adds to
the clarity of your code.
You wouldn’t document all of the factors described above for each and every method because not
all factors are applicable to every method. You would however document several of them for each
method that you write.

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 missing braces.
A trailing semi-colon is optional to end the statement
Example:
If(a == 1)
{
……
}
else
{
…..

};

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(totalCount > 1); // returns true if totalCount is more yjan 0
return (size ? size : defaultSize);

if, if-else, if else-if else Statements
The if-else class of statements should have the following form:
if (condition) {
}
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
A for statement should have the following form:
for (initialization; condition; update) {
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:
for (initialization; condition; update);
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
4. while Statements
A while statement should have the following form:
while (condition) {
statements;
}
An empty while statement should have the following form:
while (condition);
5. do-while Statements
A do-while statement should have the following form:
do {
statements;
} while (condition);
6. switch Statements
A switch statement should have the following form:
switch (condition) {
case ABC:
statements;
/* falls through */
case DEF:
statements;
break;
case XYZ:
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
A try-catch statement should have the following format:
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;

}

Techniques for Writing Clean Code
Your code might be sold to users as part of an application framework. Therefore you should aim for
clean,
professional-looking code using the following:
Document your code
Paragraph your code
Specify the order of message sends
Write short, single command lines
Use of blank lines

Use of blank spaces 

No comments:

Post a Comment