Table of Contents
Rules, are those coding standards which are necessary and required coding
practices which have been agreed between the java development group. Everyone developing
java code is expected to follow these rules.
File Names
This section lists the commonly used file suffixes and
names.
File Suffixes
The development of java software uses the following file
suffixes:
|
File Type
|
Suffix
|
|
Java Source Files
|
.java
|
|
Java Executable Archive
|
.jar
|
|
Java Bytecode
|
.class
|
Common Files
Frequently used filenames include:
|
File Name
|
Use
|
|
README
|
Brief description of the contents of the source area
|
|
MAKEFILE
|
MAKEFILE Build environment independent of any IDE,
includes
building of Javadoc source
|
Packages
Package identifiers are separated by a full stop (period).
Package names are in lower case and begin with the reverse of the Internet
domain ‘com.stateside-technology.
The package name is to be declared singular.
Source File
The source file is given the name of the primary class or
interface that is declared within the extension ‘.java’ postfixed to the
filename.
Classes
Use full English descriptions with the first letter capitalised
and using mixed case for the rest of the name
Interfaces
The java conventions for naming interfaces it to use mixed
case with the first letter of each word capitalised.
Local Variables
Use full English descriptions, the first letter of any
non-initial word in capitals.
Parameters
Use full English descriptions with the first letter of any
non-initial word in capitals. Parameters, which align to an existing field with
the same name, prefix with ‘p’ and use the above naming convention.
Attributes
Use full English for naming attributes. Make the attribute
self documenting. Field collections are to be given plural names to indicate
multiple values (arrays, etc..). Field names are to be given an acronym (this
should also be in lowercase).
Constants
Use full English for naming constants and use uppercase
only, with underscores between words. Constants are typically implemented as
‘static final’.
Member Functions
Full English descriptions, mixed case with the first
letter of any non-initial word capitalised.
Accessor Member Functions
Getter functions be prefixed with ‘get’, Boolean functions
use ‘is’
Setter functions be prefixed with ‘set’
Constructs have the same name and case as their class and
need to be strictly adhered to.
Code Comments can be broken down into three main
categories. These categories are described in the following table; each
category includes a description of its use.
|
Documentation
|
Use this before the declaration of classes, interfaces,
member functions and fields (All interfaces, classes, methods will have Javadoc
comments)
|
|
C Style
|
Use this to comment out lines of code which are either
no longer applicable or are commented out temporarily. Code which is no
longer applicable is to be removed prior to the insertion of any deltas
|
|
C++ Style
|
Use this for single line comments internally within member
functions (document business logic, declarations)
|
JavaDoc Comments
The following table describes the most used javadoc tags.
|
@author name-text
|
Adds an "Author" entry with the specified name-text
to the generated docs when the -author option is used. A doc comment may
contain multiple @author tags. You can specify one name per @author tag or
multiple names per tag. In the former case, Javadoc inserts a comma (,) and
space between names. In the latter case, the entire text is simply copied to
the generated document without being parsed. Therefore, use multiple names
per line if you want a localized name separator other than comma.
|
|
@deprecated deprecated-text
|
Adds a comment indicating that this API should no longer
be used (even though it may continue to work). Javadoc moves the deprecated-text
ahead of the description, placing it in italics and preceding it with a
bold warning: "Deprecated". The first sentence of deprecated-text
should at least tell the user when the API was deprecated and what to use
as a replacement. Javadoc copies just the first sentence to the summary
section and index. Subsequent sentences can also explain why it has been
deprecated
|
|
@exception classname
description
|
The @exception tag is a synonym for @throws.
|
|
{@link name label}
|
Inserts an in-line link that points to the specified
name.
This tag accepts exactly the same syntax for name and
label as the @see tag, described below, but generates an in-line link
rather than placing the link in the "See Also" section. This tag begins
and ends with curly braces to separate it from the rest of the in-line text.
If you need to use "}" inside the label, use the HTML entity
notation }
|
|
@param parameter-
|
- Adds a parameter to the "Parameters" section.
The name description description may be continued on the next line.
|
|
@return description
|
description Adds a "Returns" section with the description
text. This text should describe the return type and permissible range of
values.
|
|
@see reference
|
Adds a "See Also" heading with a link or text
entry that points to reference. A doc comment may contain any number
of @see tags, which are all grouped under the same heading. The @see tag has
three variations; the third form below is the most common.
|
|
@since since-text
|
Adds a "Since" heading with the specified since-text
to the generated documentation. The text has no special internal
structure. This tag means that this change or feature has existed since the
software release specified by the since-text. For example: @since
JDK1.1
|
|
@serial field-description
|
description Used in the doc comment for a default serialisable
field. An optional field-description augments the doc comment for the
field. The combined description must explain the meaning of the field and
list the acceptable values. If needed, the description can span multiple
lines.
|
|
@throws class-name
description
|
The @throws and @exception tags are synonyms. Adds a
"Throws" subheading to the generated documentation, with the class-name
and description text. The class-name is the name of the
exception that may be thrown by the method. If this class is not fully
specified, Javadoc uses the search order to look up this class.
|
Reuse Documentation
The following table describes some of the reuse tags,
which will be added to java code when it is checked into the source repository
(this feature will be in place with the reuse repository, and is only here for
documentation purposes).
|
@ReuseVersion id
|
Used to identify the particular version of the component
used as it is stored in the reuse repository
|
|
@ReuseCMetric formulae
|
Used to identify the particular formulae required to
calculate reusability of the component
|
|
@ReuseDomain name
|
Used to identify the particular domain this component is
attached to.
|
|
@ReuseCheckout name
|
Name of the person who checked out the component from
the reuse repository
|
|
@ReuseClassification
name
|
Name of the classification which the component was
originally entered into the reuse repository
|
|
@ReuseCertification
level
|
Level of certification given to the component when it
was checked out of the reuse repository
|
General Coding Guidelines
Guidelines, are those coding standards which have been written to recognise
the need to individuality and for the use of common coding practices. The
purpose of using guidelines is to provide a framework for the creation of
better code. These guidelines are not meant to impede the efforts of java
programmers when they are found to be in direct conflict with your preferences.
Java Grammar
Avoid code which embeds many operators on a single line,
this is hard to maintain
Parentheses
Parentheses are recommended for Boolean expressions to
ensure correct evaluation
Constants
Constants are in capitals with underscores between each
word and declared ‘static final’
Debugging
When debugging code use cyclomatic metric tools to
identify the conditional paths. Reuse code where possible to improve the
stability and use assertions to aid debugging
Assertions
Use assertions for:
·
Sanity checks
on methods
·
Checking
parameter passed to the method for type, value and range
·
Check the
methods correct state
·
Don’t use
assertions to check error codes; this should be handled by legitimate error
handling code
·
Use assertions
to guard pieces of code that are never logically executed.
·
Don’t forget
that assertions are compiled out of the production code
White Spaces
Blank lines improve readability by setting off sections of
code, which are logically
related.
Blank Spaces
·
Keywords
followed by a parenthesis should be separated by a single space. Blank spaces
should not be used between a method and it’s opening parenthesis. This helps to
distinguish between keywords and methods.
·
A blank space
should follow each comma in an argument list
·
All binary
operators, except ‘.’ Should be separated by their operands by a single space.
Blank spaces should never separate unary operators from their operands.
·
The expression
in a conditional statement should be separated by blank spaces
·
Casting should
not be followed by a blank space
Single Blank Lines
Single blank lines are used:
·
Between methods
·
Between the
local variable declarations in a method and its first statement
·
Before a block
or single line comment
·
Between logical
sections within a method (improves readability)
Double Blank Lines
Double blank lines are used:
·
Between
sections of a source file
·
Between class
and interface definitions (improves readability)
Exception Handling
Method Handling of exceptions
Error Handling
Error Handling should
·
Never leave a
class in an undefined state when an error condition is met
·
Be detected and
handled if it affects the execution of the rest of a routine
·
Consider
notifying the caller
·
Be tested;
don’t forget that error-handling code is code and can be defective (test cases should
be in place to exercise this code).
·
Not use an
“out” parameter for special case conditions to report errors to the caller
(always use a separate parameter, this will make it more readable and reusable).
Comments
Block comments are used to provide detailed information
relating to the block of code (either a method, data structure, interface
etc…). Block comments within a method or function should be indented at the
same level. Block comments use the “documentation” style format with the first
line of the comment block as “/**”, the comment block with a single ‘*’
followed by the textual comment and finally the last comment line ending with
‘*/’.
/**
* This is a blocked comment line
*/
Single line comments can appear on a single line indented
to the level of the code that follows. If a comment cannot be written on a
single line, it should be written as a block comment. The single line comment
should use the “C++” style of comment as ‘// comment’
// This is a single comment
Avoid trailing comments where possible.
Declaration comments differ to the use of trailing
comments in at they describe the object being used. This style of comment
should use the “C++” style as ‘// comment’ and appear on the line describing
the declaration of the object.
int testVal; // Default Test Value
Temporary removal of code for test purposes or debugging
should use the standard “C” Style comment as /* code */.
/*
int testVal; // Default Test Value
int myTest; // My Test Indicator
callMyTest();
*/
Exit points
·
Use a single
exit point where possible, document reasons for using multiple exit points
·
Avoid goto
statements
Line Spacing / Indentation
·
Line width
should not ordinarily exceed 80 characters
·
Four spaces are
used as the unit of indentation
·
Tabs should not
be used (if used they must be set to 8 spaces not 4)
·
When expressions
exceed 80 characters break it according to these general principles:
1. Break after a comma
2. Break after an operator
3. Prefer higher-level breaks to
lower-level breaks
4. Align the new line with the
beginning of the expression to the same indentation level
5. All other rules indent by 8 spaces
Braces
·
The starting
brace appears on the next line aligned with the conditional.
·
The ending
brace must be on a separate line and aligned with the conditional
·
Recommend that
all conditional constructs define a block of code for single lines of code
Simple Statements
Each line should contain at most one statement, avoid
multi-line statements where possible
int line; // Number of lines
int row; // Number of rows
Instead of using:
int line, row;
Compound Statements
·
The enclosed
statements must be indented one more level than the compound statement
·
The opening
brace should be on the next line at the same indentation level as the compound
statement
·
The closing
brace should be on it’s own line at the same indentation level as the compound
statement
·
Braces are used
around all statements including single line statements, when they are part of a
control structure (such as a conditional statement). This makes it easier to
add additional statements without introducing bugs and makes the code more
readable and reusable.
Return
A return statement with a value should not use parentheses
unless they make the return value more obvious (complex computational or
conditional behaviour).
Example:
return;
return testObject.size();
return (testObject.size() > 100
? 100 : testObject.size());
If, Else
Place the if keyword and the expression on the same
line
Example:
if (condition)
{
statements;
}
or
if (condition)
{
statements;
}
else
{
statements;
}
or
if (condition)
{
statements;
}
else if (condition)
{
statements;
}
else
{
statements;
}
While
The while construct uses the same layout format as
the if construct. The while keyword must appear on its own line,
immediately followed by its conditional expression. The statement block is
placed on the next line within braces.
Example:
while (condition)
{
statements;
}
Empty while constructs are written as ‘while (1)’
Example:
While (1)
{
statements;
}
Do..While
The do..while construct uses the same layout
format as the while construct.
Example:
do
{
statements;
} while (condition);
Switch
·
The switch construct
uses the same layout format as the if construct. The switch keyword
should appear on its own line, immediately followed by its test expression. The
statement block is placed on the next line.
·
Case statements
are indented 1 level from the switch construct
·
Case statement
blocks are indented 1 level from the case statement
·
When the case
statement falls through (does not use a break statement), add a comment to
notify the reader that the statement is expected to fall through (this
increases the readability and reduces the possibility of adding bugs)
·
Each case
statement declaration must have a blank line before the next case statement
(improves readability)
·
Each switch
construct must have a default “catch all” statement to allow for processing of
possible errors or invalid test expressions. The break statement here is
clearly redundant but prevents any fall-through errors.
Example:
switch (condition)
{
case ABC:
statements;
/* FALLTHROUGH */
case DEF:
statements;
break;
default:
statements;
break;
}
Try / Catch / Finally
·
The try/catch
construct is similar to the others. The try keyword appears on its own
line; followed by the open brace (on the next line); followed by the statement
block. Then the closing brace on its own line at the same indentation level.
·
The catch
construct appears next in the same format as the try construct.
·
The optional finally
construct is in the same format as the catch construct.
Example:
try
{
statements;
}
catch (ExceptionClass)
{
statements;
}
or
try
{
statements;
}
catch (ExceptionClass)
{
statements;
}
finally
{
statements;
}
For
·
The for construct
uses the same layout format as the while construct
·
When specifying
an endless for statement use ;;
Example:
For (initialization; condition;
update)
{
statements;
}
or
for (;;)
{
statements;
}
Placement
·
Put
declarations only at the beginning of the block.
·
Where possible
put declarations at the beginning of a method or function (to increase
readability and reusability).
·
Braces surround
a block of code.
·
The only
exception to this rule is when declaring indexes for loop processing.
·
Avoid hidden
declarations at a higher level
Suggest that the source file describes the implementation
of a single class or interface
Naming
·
Should be given
the name of the primary class or interface that is declared within and the
extension ‘.java’ should be postfixed to the filename
Documentation
·
Where files
hold more than one class list each with a brief description
·
Include the
filename at the beginning of the source file
·
Copyright
information should be added to the top of the source file. And include the
year, company name which holds the copyright
·
Reusable source
files must keep the original copyright notice intact
Naming
·
Identifiers are
separated by full stop.
·
Package names
should be in lowercase
·
Package names
should begin with the reversed internet domain name ‘com.stateside-technology
·
Package name
should be singular
Documentation
·
Externally
document the purpose of the package
·
What it does
and why for reusability
·
Include a list
of all the classes within the package and a brief description of each
·
Include a list
of all the interfaces within the package and a brief description of each
·
Include a HTML
document with this documentation within the package directory and reflect the
name of the package
Naming
·
Full English
description with the first letter capitalised and using mixed case for the rest
of the name
Visibility
·
Use package
visibility for classes internal to a component
Documentation
·
Purpose of the
class
·
History of the
classes development
·
Document
variants
·
Concurrency
issues
Order
·
Constructors
·
Finalize
·
Public member
functions
·
Protected
member functions
·
Private member
functions
·
Private fields
Minimize use of public interfaces
·
Learnability.
To understand a class you should only need to understand it’s public interface
·
Coupling.
Message coupling for instances of the class and should be reduced
·
Flexibility.
Smaller public interfaces gives greater encapsulation and therefore greater
flexibility
·
Reuse. When you
reduce the public interface you increase the classes reusability, reducing the
overall complexity metrics
Naming
·
The java
convention for naming interfaces is to use mixed case with the first letter of
each word capitalised.
Documentation
·
Describe the
interfaces purpose
·
How it should
and should not be used
Naming Member Functions
Full English Descriptions, mixed case with the first
letter of any non-initial work capitalised.
Example:
Public class CaMyClass
{
public void setMyOrdinalValue(int aVal);
public int getMyOrdinalValue();
private int myOrdinalValue;
}
Naming Accessor Member Functions
·
Getter
functions should be prefixed with ‘get’, Booleans use ‘is’
·
Setter
functions should be prefixed with ‘set’
·
Constructs have
the same name and case as their class and need to be strictly adhered to.
Visibility
Restrict member functions not required to be public to
either protected or private
Documentation
·
What does it do
and why,
·
What parameters
does it use,
·
What does it
return
·
Exceptions
·
History of code
changes
·
Invocation
example
·
Concurrency
Issues
·
Structures
Naming Fields
·
Use full
English for naming fields, self documenting
·
Field
collections should be given plural names to indicate multiple values
·
Field names
should begin with an acronym (this should also be in lowercase).
·
Constants are
typically implemented as ‘static final’, use full English and in uppercase with
underscores between words.
Visibility
·
Fields should
be declared private (encapsulate) otherwise this causes coupling and therefore
more difficult to maintain and should be avoided
·
Fields should
never be accessed directly, instead use accessor member functions.
Naming Accessors
·
Getters should
be given a prefix of ‘get’ followed by the field name unless it is a Boolean
then use ‘is’
·
Setters should
be given a prefix of ‘set’ followed by the field name. Note that field names
are mixed case with the first letter of each word in capitals.
Naming Local Fields
·
Use full
English descriptions with the first letter of any non-initial word in capitals
Declaring Local Variables
·
Declare one
local variable per line of code
·
Document local
variables with an endline comment //
Naming Parameters
·
Use full
English descriptions with the first letter of any non-initial word in capitals
·
Name parameters
that align to an existing field with the same name as the existing field and
prefixed with ‘p’ and using the above naming conventions
Documentation
·
Document what
the parameter is used for (Javadoc tags)
Miscellaneous
Test Harnesses
·
Prefix all
testing member function names with ‘test’
·
Name all member
function of the test harness consistently
·
Name all class
test harness member functions consistently
·
Create a single
point to invoke the tests
·
Document your
test harness member functions and what you expect from the test
Declaring packages
·
Use wild cards
when importing classes, only those classes you use are brought into your code
·
Explicitly
qualify the names of the classes, this however, increases the maintenance of
the code
Fundamentals of Asset Reuse Methods, Smart421 Limited.
Java Code Conventions, Sun Microsystems Inc.
Coding Conventions for C++ and Java Applications, Macadamian
Technologies Inc.
Writing Robust Java Code, AmbySoft Inc.
Draft Java Coding Standard, Doug Lea
Java Programming Style Guidelines, GeoTechnical Software
Services
Netscape’s Software Coding Standards Guide for Java,
Netscape Inc.
Java Language Specification, Sun Microsystems Inc.
The Design of Distributed Hyperlinked Programming
Documentation, Sun
Microsystems Inc.
[Return to Table Of Contents]
|