Standards and Best Practices On Java Coding
Standards and Best Practices On Java Coding
Prepared by
Control Page
Acknowledgements:
Table of Contents
1 INTRODUCTION .................................................................................................................... 5
1.1 PURPOSE ......................................................................................................................... 5
2 GENERAL CODING CONVENTIONS ................................................................................... 5
3 NAMING CONVENTIONS ...................................................................................................... 5
3.1 GENERAL CONVENTIONS................................................................................................... 5
3.1.1 Meaningful Names ..................................................................................................... 5
3.1.2 Familiar Names .......................................................................................................... 6
3.1.3 Excessively long names............................................................................................. 6
3.1.4 Dropping vowels ........................................................................................................ 6
3.1.5 Case ........................................................................................................................... 6
3.2 PACKAGE NAMES ............................................................................................................. 6
3.2.1 Convention ................................................................................................................. 6
3.3 TYPE NAMES .................................................................................................................... 6
3.3.1 Class naming ............................................................................................................. 6
3.4 INTERFACE NAMES ........................................................................................................... 6
3.4.1 Grammar .................................................................................................................... 6
3.5 METHOD NAMES ............................................................................................................... 6
3.5.1 Capitalization ............................................................................................................. 6
3.5.2 Grammar .................................................................................................................... 6
3.5.3 Accessor Methods ..................................................................................................... 7
3.6 VARIABLE NAMES ............................................................................................................. 7
3.6.1 Capitalization ............................................................................................................. 7
3.6.2 Grammar .................................................................................................................... 7
3.6.3 Instance variables ...................................................................................................... 7
3.7 CONSTANT NAMES ........................................................................................................... 7
3.7.1 Case ........................................................................................................................... 7
3.8 LIBRARY NAMING .............................................................................................................. 7
4 JAVA COMMENT STYLE CONVENTIONS........................................................................... 7
4.1 JAVA DOCS ...................................................................................................................... 7
4.2 TYPES OF COMMENTS....................................................................................................... 7
4.3 W HY HAVE COMMENTS...................................................................................................... 8
4.3 CHANGING COMMENTS ..................................................................................................... 8
5 IMPLEMENTATION COMMENTS ......................................................................................... 8
5.1 BLOCK COMMENTS ........................................................................................................... 9
5.2 SINGLE-LINE COMMENTS................................................................................................... 9
5.3 TRAILING COMMENTS ........................................................................................................ 9
5.4 END OF LINE COMMENTS .................................................................................................. 9
6 DOCUMENTATION COMMENTS .......................................................................................... 9
7 TAGS .................................................................................................................................... 10
7.1 TAG COMMENTS ............................................................................................................. 10
7.2 ORDER OF TAGS............................................................................................................. 11
7.3 ORDERING MULTIPLE TAGS.............................................................................................. 12
7.4 REQUIRED TAGS............................................................................................................. 12
8 THE USE OF PATTERNS .................................................................................................... 12
1 Introduction
In the DOL P&T SOA development environment, SDLC standards documents are developed
collaboratively by all parties impacted by and involved in the software development process. The
Architecture Group (EPAS) coordinates the process to develop the standards, and then publishes
the standards on their page of the P&T website. It is understood that given the ever-changing
environment of software development, these standards are to be viewed as living documents. In
addition, as experience evolves our best practices, it is expected that these standards documents
will evolve as well.
SDLC staff may initiate a change request to any of these standards documents by contacting (in
the form of an email), the manager of the Architecture Group.
1.1 Purpose
This document is aimed at Solution Architects, Developers, Integration Specialist and any
other role at DOL that will need to code in Java.
The Java 2 platform, Enterprise Edition (J2EE) specification is the standard for
developing, deploying, and running enterprise applications at DOL. This document
provides specific conventions and recommendations for application developers. It is
important to note that where this document is silent or requires an update, P&T staff
should fill out the SOA Standards Change Request Form (found on the EPAS website)
and submit it to EPAS to initiate a change review process for this document. Further
information can be found at Sun Microsystems Web site (java.sun.com).
The major objective of this document is to provide standards and guidelines for
application developers and designers to develop systems that are maintainable, testable,
readable and adaptable to changes in the infrastructure.
DOL uses the IBM Websphere Application Server (WAS) as its Application Server of
choice. However, it is expected that application developers will create standard J2EE
applications not relying on any particular application server extensions. WAS fully
supports all of the J2EE APIs. (In case if there is a need to use vendor specific API's,
discuss the options with EPAS before using them).
All application software written will need to pass a code review to enforce coding
conventions.
3 Naming Conventions
• Avoid abbreviations.
• Never use the name enum as a variable name as it is a keyword in Java 1.5
– refer to http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
Use meaningful names when you name a class, variable, method, or constant.
Example –
class- AddressDetails, method- addAddressDetails, variable- username,
constant- DEFAULT_CONNECTION_TYPE.
3.1.5 Case
Do not use names that differ only in case.
3.2.1 Convention
Must be in lowercase e.g. us.state.ny.labor.common.address
3.4.1 Grammar
Use nouns or adjectives when naming interfaces. First letter of each word must
be in uppercase, with the rest being in lowercase
3.5.1 Capitalization
Use lowercase for the first word and capitalize only the first letter of each
subsequent word that appears in a method name.
3.5.2 Grammar
Use verbs when naming methods. Should not have “and” or “or” in the name –
this indicates that the method does more that one task – needs refactoring.
Example –
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
3.6.1 Capitalization
Use lowercase for the first word and capitalize only the first letter of each
subsequent word that appears in a variable name.
3.6.2 Grammar
Use nouns to name variables.
3.7.1 Case
Use uppercase letters for each word and separate each pair of words with and
underscore when naming constants. Example DEFAULT_CONNECTION_TYPE.
Implementation comments are delimited by /*...*/, and //. Please refer to section 5.0.
Fixing the Javadoc comments doesn't mean just adding them where there were none
before. You should also delete misleading and trivial comments (such as documenting
setters and getters) as they engender a false sense of security. Important information
exists for inclusion in Javadoc comments, so there's no point wasting the time of potential
readers.
When you write new methods and classes, try to include some Javadoc comments to
explain what they do. Even if it's obvious to you, the next person to get the code might
thank you for the effort.
Javadoc comments can also serve as a record of what you learned about the code.
When you figure out what a particularly tricky, clever, or ugly method does (especially
a private or protected method with no implied contract), write a comment to record it for
posterity. This expands the amount of the code under your control and helps you later
when you're trying to decipher something related.
Of course, Javadoc comments should only explain the effect of a method, never the
implementation (because you might change that). If code within a method needs
explanation, use standard code comments.
5 Implementation Comments
There are four styles of implementation comments
block
single-line
trailing
end-of-line
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.
*/
if (condition)
{
/* Handle the condition. */
...
}
if (a == 2)
{
return TRUE; /* special case */
}
else
{
return isPrime(a); /* works only for odd a */
}
6 Documentation Comments
Documentation comments describe Java classes, interfaces, constructors, methods, and
fields. Each documentation comment is set inside the comment delimiters /**...*/, with
one comment per class, interface, or member. This comment should appear just before
the declaration:
/**
* The Example class provides ...
*/
public class Example
{
...
Top-level classes and interfaces are not indented, while their members are. The first line
of doc comment (/**) for classes and interfaces is not indented; subsequent
documentation comment lines each have 1 space of indentation (to vertically align the
asterisks). Members, including constructors, have 4 spaces for the first documentation
comment line and 5 spaces thereafter.
If you need to give information about a class, interface, variable, or method that isn’t
appropriate for documentation, use an implementation block comment or single-line
comment immediately after the declaration. For example, details about the
implementation of a class should go in in such an implementation block comment
following the class statement, not in the class documentation comment.
7 Tags
@author
The @author tag is not critical, because it is not included when generating the API
specification, and so it is seen only by those viewing the source code. (Version history
can also be used for determining contributors.)
@param
The @param tag is followed by the name (not data type) of the parameter, followed by a
description of the parameter. By convention, the first noun in the description is the data
type of the parameter
Tabs can be inserted between the name and description so that the descriptions line up
in a block. Dashes or other punctuation should not be inserted before the description, as
the Javadoc tool inserts one dash.
Parameter names are lowercase by convention. The data type starts with a lowercase
letter to indicate an object rather than a class. The description begins with a lowercase
letter if it is a phrase (contains no verb), or an uppercase letter if it is a sentence. End the
phrase with a period only if another phrase or sentence follows it.
Example:
@return
Omit @return for methods that return void and for constructors; include it for all other
methods, even if its content is entirely redundant with the method description. Having an
explicit @return tag makes it easier for someone to find the return value quickly.
Whenever possible, supply return values for special cases (such as specifying the value
returned when an out-of-bounds argument is supplied).
@deprecated
The @deprecated description in the first sentence should at least tell the user when the
API was deprecated and what to use as a replacement. Only the first sentence will
appear in the summary section and index. Subsequent sentences can also explain why it
has been deprecated. When generating the description for a deprecated API, the
Javadoc tool moves the @deprecated text ahead of the description, placing it in italics
and preceding it with a bold warning: "Deprecated". An @link tag should be included that
points to the replacement method.
@since
Specify the product version when the Java name was added to the API specification (if
different from the implementation). For example, if a package, class, interface or member
was added to the eCP in release 75, use:
/**
* @since release 75
*/
The Javadoc standard doclet displays a "Since" subheading with the string argument as
its text. This subheading appears in the generated text only in the place corresponding to
where the @since tag appears in the source doc comments (The Javadoc tool does not
proliferate it down the hierarchy).
A @throws tag should be included for any checked exceptions (declared in the throws
clause), as illustrated below, and also for any unchecked exceptions that the caller might
reasonably want to catch, with the exception of NullPointerException. Errors should not
be documented as they are unpredictable.
/**
* @throws IOException If an input or output exception occurred
*/
public void f() throws IOException
{
// body
}
Tag Comment
@author (classes and interfaces only, required)
@version (classes and interfaces only, required)
@param (methods and constructors only)
@return (methods only)
@exception (@throws is a synonym added in Javadoc 1.2)
@link
@since
@deprecated
Multiple @author tags should be listed in chronological order, with the creator of the
class listed at the top.
Multiple @throws tags (also known as @exception) should be listed alphabetically by the
exception names.
Multiple @see tags should be ordered as follows, which is roughly the same order as
their arguments are searched for by javadoc, basically from nearest to farthest access,
from least-qualified to fully-qualified.
An @return tag is required for every method that returns something other than void,
even if it is redundant with the method description.
DAO’s should be used to abstract and encapsulate all access to persistent stores. The
DAO must manage the connection to the datasource for all reads and writes to the
persistent store. DAO’s must use Transfer Objects (described below) to transport data to
and from their clients.
• Mediator
• Builder
• Singleton
• Adapter
• Composite
• Façade
• Proxy
More détails on these patterns can be found in the aforementioned book, or by simply
searching the Internet.
9 Appendix
JDBC alternative to Using HttpSession Data for Storing Servlet State Data
In most applications, each servlet needs only a fraction of the entire application’s state
data. As an alternative to storing the entire object in the HttpSession, use JDBC for
partitioning and maintaining the state data needed by each servlet in the application.
By default, JSP files create HttpSessions. This is in compliance with J2EE to facilitate the
use of JSP implicit objects, which can be referenced in JSP source and tags without
explicit declaration. HttpSession is one of those objects. If you do not use HttpSession in
your JSP files, then you can save some performance overhead with the following JSP
page directive:
Note: Do not load a session with heavy objects. Instead of using a session object, create
a cache object, which can hold application data. The cache object can include all the
application’s static data and user specific data. An application level cache object will be
loaded during the application startup and user specific data will be loaded when the user
logs into the application. User specific data will be available with the cache object while
the user’s session is alive.
For the sake of a consistent approach and ease of utilizing this technique, it is
recommended that caching with an application be implemented with the OSCache design
framework, which can be found on the EPAS standards website.
Failing to close and release JDBC connections can cause other users to experience long
waits for connections. Although a JDBC connection that is left unclosed will be reaped
and returned by WebSphere Application Server after a timeout period, others may have
to wait for this to occur.
Close JDBC statements when you are through with them. JDBC ResultSets can be
explicitly closed as well. If not explicitly closed, ResultsSets are released - then their
associated statements are closed.
Ensure that your code is structured to close and release JDBC resources in all cases,
even in exception and error conditions.
String concatenation is the textbook bad practice that illustrates the adverse performance
impact of creating large numbers of temporary Java objects. Because Strings are
immutable objects, String concatenation results in temporary object creation that
increases Java garbage collection and consequently CPU utilization as well.
Avoid accessing EJB entity beans from client or servlet code. Instead wrap and access
EJB entity beans in EJB session beans. This best practice satisfies two performance
concerns:
Reducing the number of remote method calls. When the client application accesses the
entity bean directly, each getter method is a remote call. A wrapping session bean can
access the entity bean locally, and collect the data in a structure, which it returns by
value.
Providing an outer transaction context for the EJB entity bean: An entity bean
synchronizes its state with its underlying data store at the completion of each transaction.
When the client application accesses the entity bean directly, each getter method
becomes a complete transaction. A store and a load follow each method. When the
session bean wraps the entity bean to provide an outer transaction context, the entity
bean synchronizes its state when outer session bean reaches a transaction boundary.
EJB homes are obtained from WebSphere Application Server through a JNDI naming
lookup. This is an expensive operation that can be minimized by caching and reusing
EJB Home objects.
When setting the deployment descriptor for an EJB Entity Bean, you can mark “getter”
methods as “Read-Only.” If a transaction unit of work includes no methods other than
”Read-Only” designated methods, then the Entity Bean state synchronization will not
invoke store.
By default, most developers deploy EJBs with the transaction isolation level set to
TRANSACTION_SERIALIZABLE. It is also the most restrictive and protected transaction
isolation level incurring the most overhead.
Some workloads do not require the isolation level and protection afforded by
TRANSACTION_SERIALIZABLE. A given application might never update the underlying
data or be run with other concurrent updaters. In that case, the application would not
Best Practice 15 - EJBs and Servlets - same JVM - “No local copies”
Because EJBs are inherently location independent, they use a remote programming
model. Method parameters and return values are serialized over RMI-IIOP and returned
by value. This is the intrinsic RMI “Call By Value” model.
WebSphere provides the “No Local Copies” performance optimization for running EJBs
and clients (typically servlets) in the same application server JVM. The “No Local Copies”
option uses “Call by Reference” and does not create local proxies for called objects when
both the client and the remote object are in the same process. Depending on your
workload, this can result in a significant overhead savings.
Instances of stateful session beans have affinity to specific clients. They will remain in the
container until they are explicitly removed by the client, or removed by the container
when they timeout. Meanwhile, the container might need to passivate inactive stateful
session beans to disk. This requires overhead for the container and constitutes a
performance hit to the application. If the passivated session bean is subsequently
required by the application, the container activates it by restoring it from disk.
1000 or so). Then display them on the screen so that you can view data while the
rest is being retrieved.
6. Running a query in a loop is normally not a good practice. If you are executing the
same query with different data, consider building a query string using UNION. You
can then execute it at the end of the loop, allowing you to execute multiple queries
with only one trip across the network to the database.
7. Consider using JOINs. They need not be resource intensive if proper indexing is
used. A denormalized schema without a join is often worse than a normalized
schema using a join. When there is redundant data, use less cycles and assure data
integrity up front by providing a framework.
8. Limit the use of correlated sub queries; often they can be replaced with a JOIN.
Best Practice 19 – Miscellaneous
• The lines of code in a Java class file should not be excessive. As a general
guideline, anything past 1200 lines may be excessive.
• The lines of code in a Java method should not be excessive. As a general
guideline, anything past 100 lines may be excessive.
• The number of characters in a line of code should not be excessive. As a
general guideline, anything past 120 characters may be excessive.
• Declare each variable on a new line.
• Declare class variable as private and use getter and setter methods to
access it outside of the class.
• Do not use System.out.println – refer to “Logging Framework”.
• Do not make fields public without good reason.
• Import individual classes specifically - do not use * imports.
• Use System.gc for explicit garbage collection in case of some memory
intensive task, though java run time performs the garbage collection by itself.
• After try and catch block use finally block to clean up or free the resources.
• Use constants in place of hard coded values.
• Avoid the use of properties (.properties extension) files. If properties are
defined with a .properties file, they can become inconsistent, poorly
documented and easily broken when the size and the complexity of the
content increases. XML configuration files are easier to organize, read and
maintain. XML configuration files can also handle and maintain complex
content in an easier way.
• Watch out for use of “==” vs. “equals()” when comparing objects.
• Use StringBuffer instead of String concatenation.
• Assign null to object references that are no longer used.
• Avoid use of deprecated
methods. http://java.sun.com/j2se/1.5.0/docs/api/deprecated-list.html
• Avoid the use of Hashtable and use Hashmap instead. The key difference
between the two is that access to Hashtable is synchronized on the table,
while access to the HashMap isn't. Another advantage is that iterator in the
HashMap is fail-safe while the enumerator for the Hashtable isn't. The third
advantage is that HashMap permits null values in it, while Hashtable doesn't.
• Avoid the use of Vector and use ArrayList instead. Both Vector and ArrayList
are considered very similar in that both of them represent an array that can
be increased and where the elements can be accessed through an index.
The big difference is that Vectors are synchronized and any method that
touches the Vector's contents is thread safe. However, using synchronization
will incur a performance hit. So, unless there is a need for a thread-safe
collection (which is not anticipated at DOL), it is recommended to use
Arraylist.
• Retrieve language specific details from the database (instead of using
properties files)
• It is recommended to avoid code formatting tools (such as those available in
RAD and WID). Following the standards described in this document should
result in code that is readable, functional and well formatted. In the future, if
code quality and formatting issues become apparent, using RAD's code
formatting capabilities to enforce the DOL specific java naming conventions,
standards and best practices can be considered.
• Read the following DOL standards documents found on the EPAS web site:
o Error handling and Logging Framework
10 References :
10.1 Bibliography:
JavaWorld. Make Bad Code Good. Farrell, Dr. John. Updated 03/23/2001. Referenced
12/04/2008. <http://www.javaworld.com/jw-03-2001/jw-0323-badcode.html>
IBM DeveloperWorks. ESQL code conventions in WebSphere Message Broker. Shen, Rachel.
Upadhyaya, Ankur. Updated 03/12/2008. Referenced 12/04/2008. IBM.
<http://www.ibm.com/developerworks/websphere/library/techarticles/0803_shen/0803_shen.html
>
Gunther, Harvey IBM Websphere Application Server Standard and Advanced Editions.
Websphere Application Server Best Practices for Performance and Scalability. Updated
9/7/2000. IBM. < http://www-
01.ibm.com/software/webservers/appserv/ws_bestpractices.pdf>
Erich Gamma, Richard Helm, Ralph Johnson, John Vlissedes. Design Patterns:
Elements of Reusable Object-Oriented Software. ON: Addison-Wesley, 1994.