Search This Blog

Wednesday, January 20, 2010

Java Coding Standards

1.1 Java Server Pages

 Use a global error page.
 Always link to Actions, never to server pages.
 Use the action attributes tag to avoid embedding Action extension.
 Use s:url to reference HTML assets.
 Use s:include to include pages
 If an image, or other swatch of markup, is being used by multiple pages,
remove it to its own server page and include it where necessary.
 Extend the UI tags as needed.
 Consider using the message resources for page titles, control labels, and so
forth, even if the application is not being localized.
 It is often useful to seperate the concern of what message to display from the concern of where to display it.
o Use the XML framework to validate input.
o Use Java script code using JS file only (by including .js file)


 Struts tags prefix should be ‘s’ only e.g. (using <%@ taglib prefix="s" uri="/struts-tags"%>)
 Use predefined CSS file for style and apply to textfield, label, dropdown, button, table and so on.
 Follow specified format of message in java script for alert/confirm/prompt messages.
 Use TILES for menu, header and footer. (These jsps are will be created by team)
 Use DISPLAY TAG for listing purpose (Example: Policy Master listing based on search criteria such as policy no, premium range and so on). Usage of the display tag will be explained.
 Use configured parameters in display tag (such as no of records per page, no of pages per list…etc) from property files.
 Use comments to make clear idea of coding. Especially for looping and logical flow.
 Give jsp name as per standard and naming conventions.
 Specify tabIndex for each and every input component in top to bottom order. (As customer will always use TAB to jump to next component.
 Use labels using property file.
 Avoid the usage of the scriplets inside the jsp pages.
 Choose the right include mechanism
 Use custom tags
 Use the JSTL Expression Language
Don’t:
1. Include any menu, header or footer JSP.
2. Write Java script code within JSP file.
3. Use style in JSP.
4. Put unnecessary alert/confirm/prompt message in java script.
5. Comments for each and every LOC.
6. Use labels as hard code value.(As our application support i18n)
7. Mix business logic with presentation


1.2 Java Script Guidelines
Use window.location.href= 'url' instead of window.navigate('url')
Do following steps to disable href links.
Write common disableAnchor (ojb, boolean) function in common Java script file.
function disableAnchor(objId, disable)
{
var obj = document.getElementById(objId);
if(obj != null)
{
if(disable)
{
var href = obj.getAttribute("href");
var onclick = obj.getAttribute("onclick");
//First we store previous value in a new attribute
if(href && href != "" && href != null)
{
obj.setAttribute('href_bak', href);
}
if(onclick != null)
{
obj.setAttribute('onclick_back', onclick);
obj.setAttribute('onclick', "void(0);");
}
obj.removeAttribute('href');
//obj.style.color="gray"; // any color
}
else
{
var hrefBack = obj.getAttribute("href_bak");
var onclickBack = obj.getAttribute("onclick_back");
if(onclickBack !=null )
{
obj.setAttribute('onclick', onclickBack);
obj.removeAttribute('onclick_back');
}
if(hrefBack !=null )
{
obj.setAttribute('href', hrefBack);
obj.removeAttribute('href_bak');
//obj.style.color="blue"; // any color
}
}
}
}









Call this function from java scripts wherever want to enable or disable href links. See below example below.
E.g
Script
disableAnchor(“Okbutton”,true); // Disable Link
disableAnchor(“Okbutton”,false); // Enable Link

JSP or HTML
Ok










1.3 Java Best Practices
Strings
1. Create strings as literals instead of creating String objects using 'new' key word whenever possible.
2. Use String.intern() method if you want to add number of equal objects whenever you create String objects using 'new' key word.
3. + Operator gives best performance for String concatenation if Strings resolve at compile time.
4. StringBuffer with proper initial size gives best performance for String concatenation if Strings resolve at run time.
5. Assign null values to String literals when no longer needed.
Using Final Keyword

1. Use the final keyword when the method must not be overridden.
2. Declare Constanta as static final.
3. Avoid Finalizers.
4. Declare method arguments as final if they are not modified in the method.

Serialization
1. Use 'transient' key word for unnecessary variables that need not be read from/written into streams.
2. When you write RMI, EJB or any other technologies that uses built in Serialization to pass objects through network, use 'transient' key word for unnescessary variables.
3. Class (static) variables ignores by Serialization process like 'transient' variables.
IO
1. Reading and writing data using default behavior of some streams that is byte by byte read/write causes slow performance.
2. Buffered input streams and buffered output streams increase performance.
3. Custom buffering increases performance significantly.
Object Creation
1. Avoid creating objects in a loop.
2. Use String literals instead of String objects (created using the 'new' keyword) if the content is same.
3. Make used objects eligible for garbage collection.
4. Do not keep inheritance chains long.
5. Accessing local variables is faster than accessing class variables
6. Use lazy evaluation, lazy object creation whenever possible.
Handling loops
1. Use integer as loop index variable.
2. Use System.arraycopy() to copy arrays.
3. Avoid method calls in loops.
4. It is efficient to access variables in a loop when compared to accessing array elements.
5. Compare the termination condition in a loop with zero if you use non-JIT or Hotspot VMs.
6. Avoid using method calls to check for termination condition in a loop
7. When using short circuit operators place the expression which is likely to evaluate to false on extreme left if the expression contains &&.
8. When using short circuit operators place the expression which is likely to evaluate to true on extreme left if the expression contains only ||.
9. Do not use exception handling inside loops
Exceptions Handling
1. Be specific while handling the exception in your catch block.
2. Be specific while throwing exception in your throws clause.
3. Do not use Exception Handling to control programming flow.
4. Very little overhead is imposed by using exception handling mechanism unless an exception occurs or thrown a new exception object explicitly.
5. Always use the finally block to release the resources to prevent resource leaks.
6. Handle exceptions locally wherever possible.
7. Do not use Exception handling in loops.
Collection

Lists:
1. Use ArrayList with proper initialization if you don't want thread safe for the collection whenever you add/remove/access objects at end and middle of collection.
2. Use Vector with proper initialization if you want thread safe for the collection whenever you add/remove/access objects at end and middle of collection.
3. Use LinkedList if you don't want thread safe for the collection whenever you add/remove/access objects at beginning of collection.
4. Use synchronized LinkedList if you want thread safe for the collection whenever you add/remove/access objects at beginning of collection.
5. Use ListIterator than Iterator and Enumeration for List types
Sets:
1. Use HashSet for maintaining unique objects if you don't want thread safe for the collection for all basic (add/remove/access) operations otherwise use synchronized HashSet for thread safe.
2. Use TreeSet for ordered and sorted set of unique objects for non-thread safe collection otherwise use synchronized TreeSet for thread safe
Maps:
1. Use HashMap for non-thread safe map collection otherwise use Hashtable for thread safe collection.
2. Use TreeMap for non-thread safe ordered map collection otherwise use synchronized TreeMap for thread safe.
JDBC
1. Use Type two drivers for two tiered applications to communicate from java client to database that gives better performance than Type1 driver.
2. Use Type four drivers for applet to database communication that is two tiered applications and three tiered applications when compared to other drivers.
3. Use Type one driver if you don't have a driver for your database. This is a rare situation because all major databases support drivers or you will get a driver from third party vendors.
4. Use Type three driver to communicate between client and proxy server ( weblogic, websphere etc) for three tiered applications that gives better performance when compared to Type 1 &2 drivers.
5. Pass database specific properties like defaultPrefetch if your database supports any of them.
6. Get database connection from connection pool rather than getting it directly
7. Use batch transactions.
8. Choose right isolation level as per your requirement. TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications.
9. Your database server may not support all isolation levels, be aware of your database server features.
10. Use PreparedStatement when you execute the same statement more than once.
11. Use CallableStatement when you want result from multiple and complex statements for a single request.
12. Use batch update facility available in Statements.
13. Use batch retrieval facility available in Statements or ResultSet.
14. Set up proper direction for processing rows.
15. Use proper getXXX() methods.
16. Close ResultSet, Statement and Connection whenever you finish your work with them.
17. Write precise SQL queries.
18. Cache read-only and read-mostly tables data.
19. Fetch small amount of data iteratively rather than whole data at once when retrieving large amount of data like searching database etc.
HTTP Session Handling Best Practices


1. Create sessions sparingly. Session creation is not free. If a session is not required, do not create one.
2. Use javax.servlet.http.HttpSession.invalidate () to release sessions when they are no longer needed.
3. Keep session size small, to reduce response times. If possible, keep session size below seven KB.
4. Use the directive <%page session="false"%> in JSP files to prevent the Enterprise Server from automatically creating sessions when they are not necessary.
5. Avoid large object graphs in an HttpSession. They force serialization and add computational overhead. Generally, do not store large objects as HttpSession variables.
6. Don’t cache transaction data in HttpSession. Access to data in an HttpSession is not transactional. Do not use it as a cache of transactional data, which is better kept in the database and accessed using entity beans. Transactions will rollback upon failures to their original state. However, stale and inaccurate data may remain in HttpSession objects. The Enterprise Server provides “read-only” bean-managed persistence entity beans for cached access to read-only data.
Using Patterns in J2EE
1. Use ServiceLocator pattern to reduce expensive JNDI lookup process.
2. Use MessageFacade/ServiceActivator pattern to avoid large method execution process.
3. Use ValueObject pattern to avoid fine grained method calls over network.
Use ValueObjectFactory/ValueObjectAssembler pattern to avoid multiple network calls for a single client request.

1.4 Struts best practices
Configuration
• Use namespaces to organize your application into logical "modules" or units of work.
• Place each namespace into its own struts configuration file
• Try to keep the Actions classes for the namespace in a common package
• Store the struts configuration for that namespace with the Actions
 If you are using JSPs, try to name the JSP folder after the Action package.
 If you using templates, bundle the templates with the Actions.
 Remember, if the namespace needs to change, you do not need to change packages or JSP folders.

• Use Exception handlers
 Local or global as needed
 Configure a global handler for Throwable

• Use global result handlers for common results
 Error
 Login

• Define a base class constants for common Result names

Action
• Validate all input fields — always on the server-side, and optionally on the clientside.
• Consider using Model Driven or POJOs if a business object layer contains most properties
• Do not use Model Driven if the business objects are not well designed or obtained through factory methods
• Write thread-safe Interceptors.
• Use a base support Action class means Extend ActionSupport
• Use SessionAware and ApplicationAware to avoid referring to servlet resources directly
• Do not embed business logic in action classes.
• Avoid chaining "business" actions.
 Bad: MoveAction = CopyAction -> DeleteAction
 Good: Extend your facade.
• Prefer BeanUtils copyValues to move data from Action properties to a
Business object.
• Consider using a JavaBean helper to encapsulate data and messages
Returned from the Model.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.