Java Coding Guidelines (PDF) by learnguy

VIEWS: 44 PAGES: 20

More Info
									NYSDOL                                               Standards and Best Practices




           Standards and Best Practices on Java Coding




                                  Prepared by


              Enterprise Planning and Architecture Strategies Team




JavaCoding Guidelines1-2.doc                                         Page 1 of 20
Version 1.2                                              Last modified: 9/14/2010
NYSDOL                                              Standards and Best Practices




Control Page




Revised Date          Author           Version No               Comments
                 Vijai Singh – (Best
 12/05/2008     practices by Bandari      1.0                   Initial draft
                       Kumar)
                                                          Revisions in response to
  1/20/2009         Vijai Singh           1.2              comments from Virtual
                                                               Review Team
 09/08/2010            EPAS                                 Draft status removed




Acknowledgements:




JavaCoding Guidelines1-2.doc                                        Page 2 of 20
Version 1.2                                             Last modified: 9/14/2010
NYSDOL                                                                                           Standards and Best Practices




                                                       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

JavaCoding Guidelines1-2.doc                                                                                         Page 3 of 20
Version 1.2                                                                                              Last modified: 9/14/2010
NYSDOL                                                                                          Standards and Best Practices


     J2EE DESIGN PATTERNS ............................................................................................................. 12
     8.1    BUSINESS DELEGATE...................................................................................................... 12
     8.2    SERVICE LOCATOR ......................................................................................................... 13
     8.3    SESSION FACADE ........................................................................................................... 13
     8.4    DATA ACCESS OBJECTS ................................................................................................. 13
     8.5    TRANSFER OBJECTS ....................................................................................................... 13
     8.6    GOF (GANG OF FOUR) PATTERNS .................................................................................. 13
9       APPENDIX ............................................................................................................................ 14
     9.1 APPENDIX A. CURENT J2EE PRODUCT VERSION INFORMATION ERROR! BOOKMARK NOT DEFINED.
     9.2. APPENDIX B. BEST PRACTICES.............................................................................................. 14
     9.3 ACRONYMS USED .................................................................................................................. 19
10      REFERENCES : ................................................................................................................... 19
     10.1 BIBLIOGRAPHY:.................................................................................................................... 19




JavaCoding Guidelines1-2.doc                                                                                       Page 4 of 20
Version 1.2                                                                                            Last modified: 9/14/2010
NYSDOL                                                          Standards and Best Practices




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

2       General Coding Conventions

        All application software written will need to pass a code review to enforce coding
        conventions.

3       Naming Conventions

        3.1     General Conventions

        3.1.1   Meaningful Names
                •   Use US English spelling.
                •   All names should be meaningful – methods must do what they say they do,
                    and no more.


JavaCoding Guidelines1-2.doc                                                     Page 5 of 20
Version 1.2                                                          Last modified: 9/14/2010
NYSDOL                                                        Standards and Best Practices


              •   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.2   Familiar Names
              Use words that exist in the terminology of the target domain. If your users refer
              to their clients as customers, then use the name “customer” for the class, not
              “client”. We will define a glossary for the common names. Please refer to 3.9
              miscellaneous sections.

      3.1.3   Excessively long names
              Use meaningful and descriptive but not excessively long names for class,
              interface, variable, or methods.

      3.1.4   Dropping vowels
              Use descriptive names and do not attempt to shorten names by removing vowels.

      3.1.5   Case
              Do not use names that differ only in case.

      3.2     Package Names

      3.2.1   Convention
              Must be in lowercase e.g. us.state.ny.labor.common.address

      3.3     Type Names

      3.3.1   Class naming
              Use nouns when naming classes. First letter of each word must be in uppercase,
              with the rest being in lowercase example-AddressDetails.

      3.4     Interface Names

      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     Method Names

      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.


JavaCoding Guidelines1-2.doc                                                   Page 6 of 20
Version 1.2                                                        Last modified: 9/14/2010
NYSDOL                                                         Standards and Best Practices


      3.5.3   Accessor Methods
              Follow the JavaBeans conventions for naming property accessor methods.

              Example –
              public void setName(String name) {
               this.name = name;
              }
              public String getName() {
              return name;
              }


      3.6     Variable Names

      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.6.3   Instance variables
              Qualify instance variables with “this” to distinguish them from local variables and
              parameters.

      3.7     Constant Names

      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.


      3.8     Library Naming
              Library names must match the name of the containing project. For example, if
              you are creating a project with some utility functions and the name of the project
              is Utilities, the library name for the project must be Utilities.jar

4     Java Comment Style Conventions

      4.1     Java Docs
      Java doc (java-generated documentation files) is a utility provided with most Java
      Development Kits which can be given some Java source code, and will produce some
      HTML pages which describe the functions of the various classes, methods, and variables
      used based on the comments within the code. It is useful to learn about the detail of how
      a piece of software has been implemented

      4.2     Types of Comments
      There are two types of comments.

      (1) implementation comments
      (2) documentation comments


JavaCoding Guidelines1-2.doc                                                    Page 7 of 20
Version 1.2                                                         Last modified: 9/14/2010
NYSDOL                                                            Standards and Best Practices


      Implementation comments are delimited by /*...*/, and //. Please refer to section 5.0.

      Documentation comments (known as “doc comments”) are delimited by /**...*/.
      Documentation comments can be extracted to HTML files using the javadoc tool.

      4.3       Why have comments
      Comment 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.

      Comment conventions improve the readability of the software, allowing engineers to
      understand new code more quickly and thoroughly, and allow the creation of readable
      javadocs.

      4.3       Changing Comments
      You never realize a comment's importance until you need to read it. Javadoc comments
      are important for the code authors to help them remember what the code/class/parameter
      should do. Pieces of information particularly important to include are:

           Whether an object parameter may be null, and what it means if it is
           Whether a parameter needs to be mutable or not
           Whether a return value is mutable
           Whether a return value may be null
           Whether changes to the return value affect the returner's internal state

      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



JavaCoding Guidelines1-2.doc                                                       Page 8 of 20
Version 1.2                                                            Last modified: 9/14/2010
NYSDOL                                                            Standards and Best Practices


        5.1      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 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.
*/

        5.2      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

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


        5.3      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:


if (a == 2)
{
         return TRUE;                                     /* special case */
}
else
{
         return isPrime(a);                               /* works only for odd a */
}

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


6       Documentation Comments
        Documentation comments describe Java classes, interfaces, constructors, methods, and
        fields. Each documentation comment is set inside the comment delimiters /**...*/, with

JavaCoding Guidelines1-2.doc                                                        Page 9 of 20
Version 1.2                                                             Last modified: 9/14/2010
NYSDOL                                                               Standards and Best Practices


        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.

        Documentation comments should not be positioned inside a method or constructor
        definition block, because Java associates documentation comments with the first
        declaration after the comment..

7       Tags

        7.1     Tag Comments

        @author

        You can provide one @author tag or multiple @author tags.

        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:

JavaCoding Guidelines1-2.doc                                                          Page 10 of 20
Version 1.2                                                                Last modified: 9/14/2010
NYSDOL                                                          Standards and Best Practices


       @param ch                the character to be tested
       @param observer          the image observer to be notified

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

       @throws (@exception was the original tag)

       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
 }


       7.2      Order of Tags
       Include tags in the following order


JavaCoding Guidelines1-2.doc                                                     Page 11 of 20
Version 1.2                                                           Last modified: 9/14/2010
NYSDOL                                                           Standards and Best Practices


    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


       7.3     Ordering multiple tags
       If desired, groups of the tags listed below, can be separated from the other tags by a
       blank line with a single asterisk.

       Multiple @author tags should be listed in chronological order, with the creator of the
       class listed at the top.

       Multiple @param tags should be listed in argument-declaration order. This makes it
       easier to visually match the list to the declaration.

       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.

       7.4     Required Tags
       An @param tag is required for every parameter, even when the description is obvious.

       An @return tag is required for every method that returns something other than void,
       even if it is redundant with the method description.

8      The Use of Patterns
       Applications built for Department of Labor should use the core J2EE patterns to leverage
       proven solutions and provide a common vocabulary. The following is a list of common
       patterns that should be used where appropriate.

       J2EE Design Patterns

       8.1     Business Delegate
       The business delegate pattern must be used between the server side presentation
       (second tier) and the server side business logic (third tier) tiers to minimize coupling
       between the two layers. The business delegate isolates the second tier from performing
       naming and lookup of services, handling exceptions like remote exceptions thrown by the
       business services, performing retry or recovery operations and caching results and
       references of business services.




JavaCoding Guidelines1-2.doc                                                     Page 12 of 20
Version 1.2                                                           Last modified: 9/14/2010
NYSDOL                                                         Standards and Best Practices


      8.2       Service Locator
      The service locator pattern is used in the server side business logic (third tier) tier to
      transparently locate business components and services in a uniform manner. The
      business delegate must use a service locator to encapsulate the implementation details
      of a business service lookup. When the business delegate needs to lookup a business
      service, it delegates the lookup functionality to the service locator. The Service locator
      pattern must be used to lookup all EJB components, JDBC datasources and all JMS
      components.

      8.3       Session Facade
      A session façade encapsulates business components in the third tier and exposes a
      coarse grained service to remote clients. Clients access the session façade instead of
      accessing business components directly. The business delegate is a client side
      abstraction for a session façade. The business delegate proxies client requests to a
      session façade that provides the requested service.

      8.4       Data Access Objects

      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.

      8.5       Transfer Objects
      Transfer objects should be used when multiple data elements must be transferred across
      tiers. A Transfer object in most cases is simply a serializable plain old Java object that
      contains several members to aggregate and carry all the data in a single method call.

      8.6       GOF (Gang of Four) Patterns
      DOL owns Rational Software Architect (RSA) for its capabilities as an advanced model-
      driven development tool. The book "Design Patterns: Elements of Reusable Object-
      Oriented Software", by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides,
      (also known as the Gang of Four), is famous for laying out 23 classic software design
      patterns, all of which are incorporated into RSA. The following patterns are particularly
      useful to DOL in its SOA development environment.

            •   Mediator
            •   Builder
            •   Singleton
            •   Adapter
            •   Composite
            •   Façade
            •   Proxy




JavaCoding Guidelines1-2.doc                                                   Page 13 of 20
Version 1.2                                                         Last modified: 9/14/2010
NYSDOL                                                          Standards and Best Practices


      More détails on these patterns can be found in the aforementioned book, or by simply
      searching the Internet.

9     Appendix


      9.1. Appendix B. Best Practices

      Best Practice 1 - Do not store large object graphs in HttpSession

      Large applications require using persistent HttpSessions. However, there is a cost. An
      HttpSession must be read by the servlet whenever it is used and rewritten whenever it is
      updated. This involves serializing the data and reading it from and writing it to a
      database. In most applications, each servlet requires only a fraction of the total session
      data. However, by storing the data in the HttpSession as one large object, an application
      forces WebSphere Application Server to process the entire HttpSession object each time.

      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.

      Best Practice 2 - Release HttpSessions when finished

      HttpSession objects live inside the WebSphere servlet engine until:

      •   The application explicitly and programmatically releases it using the API,
          javax.servlet.http.HttpSession.invalidate (); quite often, programmatic invalidation is
          part of an application logout function.

      •   WebSphere Application Server destroys the allocated HttpSession when it expires
          (by default, after 1800 seconds or 30 minutes). WebSphere Application Server can
          only maintain a certain number of HttpSessions in memory. When this limit is
          reached, WebSphere Application Server serializes and swaps the allocated
          HttpSession to disk. In a high volume system, the cost of serializing many abandoned
          HttpSessions can be quite high.

      Best Practice 3 - Do not create HttpSessions in JSPs by default

      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:

      <%@ page session="false"%>

      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.


JavaCoding Guidelines1-2.doc                                                    Page 14 of 20
Version 1.2                                                          Last modified: 9/14/2010
NYSDOL                                                          Standards and Best Practices



      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.

      Best Practice 4 - Minimize synchronization in Servlets

      Servlets are multi-threaded. Servlet-based applications have to recognize and handle
      this. However, if large sections of code are synchronized, an application effectively
      becomes single threaded, and throughput decreases.

      Best Practice 5 - Do not use SingleThreadModel

      SingleThreadModel is a tag interface that a servlet can implement to transfer its
      reentrancy problem to the servlet engine. As such, javax.servlet.SingleThreadModel is
      part of the J2EE specification. The WebSphere servlet engine handles the servlet’s
      reentrancy problem by creating separate servlet instances for each user. Because this
      causes a great amount of system overhead, SingleThreadModel should be avoided.

      Developers typically use javax.servlet.SingleThreadModel to protect updateable servlet
      instances in a multithreaded environment. The better approach is to avoid using servlet
      instance variables that are updated from the servlet’s service method.

      Best Practice 6 - Use JDBC connection pooling

      To avoid the overhead of acquiring and closing JDBC connections, WebSphere
      Application Server provides JDBC connection pooling based on JDBC 2.0. Servlets
      should use WebSphere Application Server JDBC connection pooling instead of acquiring
      these connections directly from the JDBC driver. WebSphere Application Server JDBC
      connection pooling involves the use of javax.sql.DataSources.

      Best Practice 7 - Reuse datasources for JDBC connections

      A javax.sql.DataSource is obtained from WebSphere Application Server through a JNDI
      naming lookup. Avoid the overhead of acquiring a javax.sql.DataSource for each SQL
      access. This is an expensive operation that will severely impact the performance and
      scalability of the application. Instead, servlets should acquire the javax.sql.DataSource in
      the Servlet.init() method (or some other thread-safe method) and maintain it in a common
      location for reuse.

      Best Practice 8 - Release JDBC resources when done

      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.

      Best Practice 9 - Minimize use of System.out.println


JavaCoding Guidelines1-2.doc                                                    Page 15 of 20
Version 1.2                                                          Last modified: 9/14/2010
NYSDOL                                                          Standards and Best Practices


      Because it seems harmless, this commonly used application development legacy is
      overlooked for the performance problem it really is. Because System.out.println
      statements and similar constructs synchronize processing for the duration of disk I/O,
      they can significantly slow throughput. Figure 10c shows the adverse performance impact
      of inserting System.out.println statements into an application.

      Best Practice 10 - Avoid String concatenation “+=”

      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.

      The textbook solution is to use java.lang.StringBuffer instead of string concatenation.

      Best Practice 11 - Access entity beans from session beans

      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.

      Best Practice 12 - Reuse EJB homes

      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.

      Best Practice 13 - Use “Read-Only” methods where appropriate

      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.

      Best Practice 14 - Reduce the transaction isolation level where
      Appropriate

      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

JavaCoding Guidelines1-2.doc                                                    Page 16 of 20
Version 1.2                                                          Last modified: 9/14/2010
NYSDOL                                                           Standards and Best Practices


      have to be concerned with dirty, non-repeatable, or phantom                            reads.
      TRANSACTION_READ_UNCOMMITTED would probably be sufficient.

      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.

      Best Practice 16 - Remove stateful session beans when finished

      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.

      Best Practice 17 - Don’t use Beans.instantiate() to create new bean instances

      The method, java.beans.Beans.instantiate(), will create a new bean instance either by
      retrieving a serialized version of the bean from disk or creating a new bean if the
      serialized form does not exist. The problem, from a performance perspective, is that each
      time java.beans.Beans.instantiate is called the file system is checked for a serialized
      version of the bean. As usual, such disk activity in the critical path of your web request
      can be costly. To avoid this overhead, simply use “new” to create the instance.

      Best Practice 18 – Fine tuning SQLs

      (In no particular order):
      1. Always use explicit joins. (If you mean INNER JOIN, then use INNER JOIN). Don’t
         use just a plain "JOIN". Never use a comma join. Also, keep join conditions in an ON
         or USING clause; they should not go in the WHERE clause.
      2. Always define field names. Don’t use SELECT * or INSERT INTO table VALUES. It
         can be difficult, and even more so given that mysqldump does not specify INSERT
         fields. However, if it's important enough to save in a text file (i.e., its seed data or a
         migration script), then use explicit field names.
      3. Always use the database server's timestamp (Web servers may have disparate
         times). Reports may come from different servers than the inserted data.
      4. Store IPs as integers with INET_ATON and retrieve them with INET_NTOA.
      5. When doing reports, the network traffic is usually the biggest bottleneck. If you're
         going to receive information, it's better to receive it in chunks, which will likely be
         larger than a logical piece. For example, if your report involves all 50 US states, get
         them all at once instead of making 50 separate connections for each state. If the
         dataset is very large and you do not want to stare at a blank page while the report is
         loading, use paging with LIMIT to grab a specific number of entries (for example,


JavaCoding Guidelines1-2.doc                                                      Page 17 of 20
Version 1.2                                                            Last modified: 9/14/2010
NYSDOL                                                           Standards and Best Practices


          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.

JavaCoding Guidelines1-2.doc                                                     Page 18 of 20
Version 1.2                                                           Last modified: 9/14/2010
NYSDOL                                                           Standards and Best Practices


                  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

      9.2 Acronyms Used

                  RAD        Rational Application Developer
                  WID        WebSphere Integration Developer
                  SDLC       Software Development Life Cycle
                  J2EE       Java 2 Enterprise Edition
                  ARB        Architecture Review Board
                  WAS        WebSphere Application Server
                  RSA        Rational Software Architect

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>

      Wikipedia. Coding conventions. Updated 11/18/2008. Referenced 12/04/2008
      <http://en.wikipedia.org/wiki/Code_conventions>

      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
      >

      Guidelines for writing Javadoc documentation comments. Plosch, Reinhold. Weinreich,
      Rainer. Update 8/2/2000. Referenced 12/04/2008. < http://www.swe.uni-
      linz.ac.at/teaching/lva/ss02/praktikum/pk246521/java_doc_guidelines.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>

      Sun. “Deprecated List(Java 2 Platform SE v 1.5)”. 2004.
      <http://java.sun.com/j2se/1.5.0/docs/api/deprecated-list.html>


JavaCoding Guidelines1-2.doc                                                      Page 19 of 20
Version 1.2                                                            Last modified: 9/14/2010
NYSDOL                                                        Standards and Best Practices


      Sun. “Core J2EE Patterns” . 2001-
      2002. http://java.sun.com/blueprints/corej2eepatterns/Patterns/index.html>

      Erich Gamma, Richard Helm, Ralph Johnson, John Vlissedes. Design Patterns:
      Elements of Reusable Object-Oriented Software. ON: Addison-Wesley, 1994.




JavaCoding Guidelines1-2.doc                                                  Page 20 of 20
Version 1.2                                                        Last modified: 9/14/2010

								
To top