Java Coding Standards

advertisement
Infosys
QUALITY SYSTEM DOCUMENTATION
References
JAVA CODING STANDARDS
JAN, 2008
INFOSYS TECHNOLOGIES LIMITED,
Bangalore.
Document No.:
Authorized by:
QSD/REF/919
Satyendra Kumar
Ver.Rev.No.
Signature:/
Date
9.01
Jan 3rd 2008
COPYRIGHT NOTICE
This Quality System Documentation is the property of Infosys Technologies Limited. All ideas and information
contained within these documents are the intellectual property rights of Infosys Technologies Limited. These
documents are not for general distribution and are meant for use only for the person they are specifically issued
to. These documents shall not be loaned to anyone, within or outside Infosys, including its customers. Copying
or unauthorized distribution of these documents, in any form or means including electronic, mechanical,
photocopying or otherwise is illegal.
Infosys Technologies Limited
Hosur Road
Electronic City, 3rd Cross
Bangalore 561 100
India.
Telephone: 91 80 2852 0261
Fax: 91 80 2852 0362
Website: http://www.infosys.com
Infosys
Java Coding Standards
© Infosys Technologies Limited
JAVA CODING STANDARDS REVISION LIST
Ver.Rev
8.00
Date
June 03 1997
Author
C Ananth
Description
Original document
8.10
July 31st 2002
9.00
Jan 3rd 2008
9.01
Aug 20th 2008
K.Chandrasekar
Reddy
Chetana Amancharla,
Jyotsna Prabhu,
Ashish Kumar Jain
McCrazy Zhou
Changes to incorporate all project
standards into the QSD document
Added new standards based on inputs
from the BCM Star group. Removed
section on Visual Age IDE
Modify to use in Zions Projects
References
QSD/REF/919
Ver. Rev. 9.01
1
Infosys
Java Coding Standards
© Infosys Technologies Limited
TABLE OF CONTENTS
1.
INTRODUCTION .......................................................................................................................................... 1
2.
NAMING CONVENTIONS ........................................................................................................................... 1
3.
2.1
Package Names ....................................................................................................................................... 1
2.2
File Names .............................................................................................................................................. 1
2.3
Class/Interface Names ............................................................................................................................. 1
2.4
Field Names ............................................................................................................................................ 1
2.5
Constants ................................................................................................................................................. 2
2.6
Method Names ........................................................................................................................................ 2
2.7
Arrays ...................................................................................................................................................... 3
2.8
List/Map .................................................................................................................................................. 3
2.9
Abbreviations and Acronyms .................................................................................................................. 3
2.10
Use of Meaningful Names....................................................................................................................... 3
2.11
Length of Names ..................................................................................................................................... 3
FILE ORGANIZATION ................................................................................................................................. 4
3.1
4.
Java Source Files ..................................................................................................................................... 4
STATEMENTS............................................................................................................................................... 4
4.1
Package and Import Statement ................................................................................................................ 4
4.2
Class and Interfaces ................................................................................................................................. 4
4.3
Methods ................................................................................................................................................... 5
4.4
Types ....................................................................................................................................................... 5
4.5
Variables ................................................................................................................................................. 5
4.6
Loops....................................................................................................................................................... 5
4.7
Conditionals ............................................................................................................................................ 6
4.8
Miscellaneous .......................................................................................................................................... 6
5.
LAYOUT ........................................................................................................................................................ 6
6.
COMMENTS .................................................................................................................................................. 7
7.
6.1
Beginning Comments .............................................................................................................................. 7
6.2
Comments for a Class ............................................................................................................................. 8
6.3
Comments for a Method .......................................................................................................................... 8
6.4
Single Line Comments ............................................................................................................................ 9
6.5
Block Comments ..................................................................................................................................... 9
6.6
End of Line Comments ........................................................................................................................... 9
CODING STYLE ........................................................................................................................................... 9
7.1
Indentation .............................................................................................................................................. 9
7.2
Wrapping Lines ..................................................................................................................................... 10
7.3
Try-catch-finally ................................................................................................................................... 10
References
QSD/REF/919
Ver. Rev. 9.01
2
Infosys
Java Coding Standards
© Infosys Technologies Limited
8.
BEST PRACTICES ...................................................................................................................................... 10
8.1
Exceptions ............................................................................................................................................. 10
8.2
Catch() Statement .................................................................................................................................. 10
8.3
Empty Catch Blocks() ........................................................................................................................... 11
8.4
Logging ................................................................................................................................................. 11
8.5
String vs StringBuffers .......................................................................................................................... 12
8.6
JDBC Statement .................................................................................................................................... 12
8.7
Boolean Objects .................................................................................................................................... 12
8.8
Synchronized(this) ................................................................................................................................ 12
8.9
Iterations................................................................................................................................................ 14
9.
SIZE .............................................................................................................................................................. 14
9.1
Class Size .............................................................................................................................................. 14
9.2
Method Size .......................................................................................................................................... 14
10.
DECLARATIONS .................................................................................................................................... 14
10.1
Number Per Line ................................................................................................................................... 14
10.2
Initialising Variables ............................................................................................................................. 15
11.
PACKAGES.............................................................................................................................................. 15
12.
PROGRAMMING PRACTICES .............................................................................................................. 15
12.1
Providing Access to Instance and Class Variables ................................................................................ 15
12.2
Access Specifies for a class ................................................................................................................... 15
12.3
Referring to Class Variables and Methods ............................................................................................ 15
12.4
Constants ............................................................................................................................................... 15
12.5
Variable Assignments ........................................................................................................................... 15
12.6
Null checks ............................................................................................................................................ 16
12.7
String comparison ................................................................................................................................. 16
12.8
Object instantiation ............................................................................................................................... 16
12.9
Unnecessary method calls ..................................................................................................................... 17
12.10
Exception handling............................................................................................................................ 17
12.11
Commented code blocks ................................................................................................................... 18
12.12
System.out.println () .......................................................................................................................... 18
13.
MISCELLANEOUS ................................................................................................................................. 18
13.1
Import of Classes................................................................................................................................... 18
13.2
Multiple decisions ................................................................................................................................. 18
13.3
Error Messages ...................................................................................................................................... 18
13.4
Performance related .............................................................................................................................. 19
References
QSD/REF/919
Ver. Rev. 9.01
3
Infosys
Java Coding Standards
© Infosys Technologies Limited
References
QSD/REF/919
Ver. Rev. 9.01
4
Infosys
Java Coding Standards
© Infosys Technologies Limited
1. INTRODUCTION
The objective of this document is to address the conventions required for packages written in Java
to avoid most common errors
to make code maintainable
to make code readable
It also tries to address some of the issues involved in designing and programming in Java. This is by no
means a final word on these issues.
2. NAMING CONVENTIONS
2.1 Package Names
i. Package name should be in all lower case. The initial package name representing the domain name must
be in lower case.
Eg.
package com.company.application.ui;
2.2 File Names
i. The Java files must have .java extension.
ii. Java source file names are of the form:
ClassOrInterfaceName.java
Where ClassOrInterfaceName is exactly the name of the public class or interface defined in the source
file.
2.3 Class/Interface Names
One file can contain only one public class. But this class can have private helper classes defined in the
same file. To other members of the package in which the class belongs, only the public class will be
available. The names of these private classes should be appropriately named.
All type names (classes and interfaces) should use the InfixCaps style. Start with an upper-case letter, and
capitalize the first letter of any subsequent word in the name, as well as any letters that are part of an
acronym.
All other characters in the name are lower-case. Do not use underscores to separate words. Class names
should be nouns or noun phrases. Interface names depend on the salient purpose of the interface. If the
purpose is primarily to endow an object with a particular capability, then the name should be an adjective
(ending in -able or -ible if possible) that describes the capability; e.g., Searchable, Sortable,
NetworkAccessible. Otherwise use nouns or noun phrases.
Eg.
// GOOD type names:
LayoutManager, AWTException, ArrayIndexOutOfBoundsException
// BAD type names:
ManageLayout // verb phrase
awtException // first letter lower-case
array_index_out_of_bounds_exception // underscores
2.4 Field Names
Names of non-constant fields (reference types, or non-final primitive types) should use the infixCaps style.
Start with a lower-case letter, and capitalize the first letter of any subsequent word in the name, as well as
any letters that are part of an acronym. All other characters in the name are lower-case. Do not use
underscores to separate words. When the type of the field is Boolean, the names can be an adjective. Else
the names should be nouns or noun phrases.
References
QSD/REF/919
Ver. Rev. 9.01
1 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
Examples:
boolean resizable;
char recordDelimiter;
Names of fields being used as constants should be all upper-case, with underscores separating words.
Examples:
MIN_VALUE, MAX_BUFFER_SIZE, OPTIONS_FILE_NAME
One-character field names should be avoided except for temporary and looping variables. In these cases,
use:
b for a byte
c for a char
d for a double
e for an Exception object
f for a float
g for a Graphics object
i, j, k, m, n for integers
p, q, r, s for String, StringBuffer, or char[] objects
An exception is where a strong convention for the one-character name exists, such as x and y for screen
coordinates.
Avoid variable l (“el”) because it is hard to distinguish it from 1 (“one”) on some printers and displays.
2.5 Constants
2.5.1 Constants should be written in upper case letters only. Underscore can be used to separate
meaningful words. The names should be self- explanatory. Write comments if the names are not self
explanatory.
Eg.
final int LOGIN_SUCCESS = 1;
2.5.2 Associated constants (final variables) should be prefixed by a common type name.
Eg.
final int COLOR_RED = 1;
final int COLOR_GREEN = 2;
final int COLOR_BLUE = 3;
2.6 Method Names
Method names should use the infixCaps style. Start with a lower-case letter, and capitalize the first letter of any
subsequent word in the name, as well as any letters that are part of an acronym. All other characters in the name
are lower-case. Do not use underscores to separate words. Note that this is identical to the naming convention
for non-constant fields; however, it should always be easy to distinguish the two from context. Method names
should be imperative verbs or verb phrases.
Examples:
// GOOD method names:
showStatus(), drawCircle(), addLayoutComponent()
// BAD method names:
mouseButton() // noun phrase; doesn’t describe function
DrawCircle() // starts with upper-case letter
add_layout_component() // underscores
// The function of this method is unclear. Does it start the
// server running (better: startServer()), or test whether or not
// it is running (better: isServerRunning())?
serverRunning() // verb phrase, but not imperative
A method to get or set some property of the class should be called getProperty() or setProperty()
References
QSD/REF/919
Ver. Rev. 9.01
2 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
respectively, where Property is the name of the property.
Examples:
getHeight(), setHeight()
A method to test some boolean property of the class should be called isProperty(), where Property
is the name of the property.
Examples:
isResizable(), isVisible()
2.7 Arrays
Arrays should always be specified using the form and the maximum length of the array name is 30
characters.
<data type>[][]…[] arrayname;
Eg.
int [] companyNames;
double [][] salary;
The form given below must NOT be used:
Eg.
int myArray [];
//WRONG USAGE!
2.8 List/Map
Eg. List<String> sampleList = new ArrayList<String>;
Map<Integer, String> sampleMap = new Hashmap<Integer, String>;
2.9 Abbreviations and Acronyms
Eg. exportHTMLSource();
openDVDPlayer();
// NOT: exportHtmlSource();
// NOT: openDvdPlayer();
Note: Try to avoid using two or more abbreviations in one field or class name.
2.10 Use of Meaningful Names

Programmer defined names should be functionally meaningful, and should indicate the purpose of the
variable/control/method in question.

Avoid cryptic names, even in case of scratch pad variables or counters.

Bad or cryptic names waste programmer effort. Time is spent in just understanding the role of the
variable/control/method rather than in understanding functionality or solving a problem.

Complement names must be used for complement entities Eg. get/set, add/remove, create/destroy,
start/stop, insert/delete, increment/decrement, old/new, begin/end, first/last, up/down, min/max,
next/previous, old/new, open/close, show/hide, suspend/resume, etc.

Abbreviations in names should be avoided
Eg. computeAverage();
ActionEvent event;
// NOT: compAvg();
// NOT: ActionEvent e;
2.11 Length of Names
Identifiers must be as short as possible without obscuring their meaning, preferably 40 characters or less.
Excessively long variable names are cumbersome and irritating for programmers to use, hence chances of
error during coding are higher.
References
QSD/REF/919
Ver. Rev. 9.01
3 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
3. FILE ORGANIZATION
A file consists of sections that should be separated by blank lines and optional comments identifying each
section.
3.1 Java Source Files
i. Java source files should have the extension .java.
ii. File content must be kept within 150 columns.
150 columns is the common dimension for editors, terminal emulators, printers and debuggers,
and files that are shared between several developers should keep within these constraints. It improves
readability when unintentional line breaks are avoided when passing a file between programmers
iii. Each Java source file contains a single public class or interface. When private classes and interfaces are
associated with a public class, these can be put in the same source file as the public class. The public class
should be the first class or interface in the file.
Java source files should have the following ordering
 Beginning Comments
 Package and import statements
 Class and interface declarations
 Class (static) variables. The order of these variables should be public, protected and then private
 Instance variables. The order of these variables should be public, protected and then private
 Constructors
 Static Methods - The order of these methods should be public, protected and then private.
 Methods - The order of these methods should be public, protected and then private.
4. STATEMENTS
4.1 Package and Import Statement


The package statement must be the first statement of the file. All files should belong to a specific
package.
Imported classes should always be listed explicitly.
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
Eg.

// NOT: import java.util.*;
Import statements should be grouped together by package name. A single blank line may be used to
separate groups of import statements.
4.2 Class and Interfaces

Class and Interface declarations should be organized in the following manner:
1.
Class/Interface documentation.
2.
Class or interface statement.
3.
Class (static) variables in the order public, protected, package (no access modifier), private.
4.
Instance variables in the order public, protected, package (no access modifier), private.
5.
Constructors.
6.
Static Methods - The order of these methods should be public, protected and then private.
7.
Methods - The order of these methods should be public, protected and then private.
References
QSD/REF/919
Ver. Rev. 9.01
4 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
4.3 Methods

Methods Modifiers should be given in the following order
<access>
static
abstract
synchronized
The <access> modifier (if present) must be the first modifier.
Eg.
<unusual>
final
native
public static double square(double a);
// NOT: static public double square(double a);
4.4 Types

Type conversions must always be done explicitly. Never rely on implicit type conversion.
Eg.
floatValue = (float) intValue;
// NOT: floatValue = intValue;
Array specifiers must be attached to the type not the variable.
Eg.
int[] a = new int[20];
// NOT: int a[] = new int[20]
4.5 Variables



Variables should be initialized where they are declared.
This ensures that variables are valid at any time. Sometimes it is impossible to initialize a variable to a
valid value where it is declared. In these cases it should be left uninitialized rather than initialized to
some phoney value.
Class variables should never be declared public
The concept of Java information hiding and encapsulation is violated by public variables. Use private
variables and access functions instead. One exception to this rule is when the class is essentially a data
structure, with no behavior (equivalent to a C++ struct). In this case it is appropriate to make the
class' instance variables public

Arrays should be declared with their brackets next to the type
Eg.
double[] vertex;
// NOT: double vertex[];
int[] count;
// NOT: int count[];
public static void main(String[] arguments)
public double[] computeVertex()
4.6 Loops

Only loop control statements must be included in the for() construction.
Eg.

sum = 0;
// NOT: for (i = 0, sum = 0; i < 100; i++)
for (i = 0; i < 100; i++)
sum += value[i];
The use of do-while loops can be avoided.
do-while loops are less readable than ordinary while loops and for loops since the conditional is at the
bottom of the loop. The reader must scan the entire loop in order to understand the scope of the loop.
In addition, do-while loops are not needed. Any do-while loop can easily be rewritten into a while loop
or a for loop. Reducing the number of constructs used enhance readability.

The use of break and continue in loops should be avoided
References
QSD/REF/919
Ver. Rev. 9.01
5 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
4.7 Conditionals

The conditional should be put on a separate line.
Eg.
if (isDone)
{
doCleanup();
}
// NOT: if (isDone) doCleanup();
4.8 Miscellaneous

The use of magic numbers in the code should be avoided. Numbers other than 0 and 1can be
considered declared as named constants instead.
Eg.
private static final int TEAM_SIZE = 11;
Player[] players = new Player[TEAM_SIZE];
// NOT: Player[] players = new Player[11];
If the number does not have an obvious meaning by itself, the readability is enhanced by introducing a
named constant instead.

Floating point constants should always be written with decimal point and at least one decimal.
Eg.

double total = 0.0;
double speed = 3.0e8;
double sum;
sum = (a + b) * 10.0;
// NOT: double total = 0;
// NOT: double speed = 3e8;
Floating point constants should always be written with a digit before the decimal point.
Eg.
double total = 0.5;
// NOT: double total = .5;
5. LAYOUT

The class and interface declarations should have the following form:
Eg.
class
Serializable
{
...
}
Rectangle
extends
Shape
implements
Cloneable,
This follows from the general block rule above. Note that it is common in the Java developer
community to have the opening bracket at the end of the line of the class keyword. This is not
recommended.

Method definitions should have the following form:
Eg.

public void someMethod() throws SomeException
{
...
}
White Space
Operator should be surrounded by a space character
Java reserved words should be followed by a white space
Commas should be followed by a space character
Colon should be surrounded by a space character
Semicolon in for statement should be followed by a white space
References
QSD/REF/919
Ver. Rev. 9.01
6 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
Eg

a = (b + c) * d;
// NOT: a=(b+c)*d
while (true) {
// NOT: while(true){
...
doSomething(a, b, c, d);
// NOT: doSomething(a,b,c,d);
case 100 :
// NOT: case 100:
for (i = 0; i < 10; i++)
{
// NOT: for(i=0;i<10;i++)
}
Logical units within a block should be separated by one blank line.
Eg.
// Create a new identity matrix
Matrix4x4 matrix = new Matrix4x4();
// Precompute angles for efficiency
double cosAngle = Math.cos(angle);
double sinAngle = Math.sin(angle);
// Specify matrix as
matrix.setElement(1,
matrix.setElement(1,
matrix.setElement(2,
matrix.setElement(2,
a rotation transformation
1, cosAngle);
2, sinAngle);
1, -sinAngle);
2, cosAngle);
// Apply rotation
transformation.multiply(matrix);
6. COMMENTS
Write neat, readable and meaningful comments. Use the javadoc format of /** Comments */. This
enables a documentation of the class in HTML format to be carried out by running the javadoc
documentation tool provided by JDK. Note that the javadoc generates documentation only for variables
and methods with public, protected or private protected access. Any comments relating to private or
default package variables and methods are not translated to the output documentation. This is in keeping
with the object oriented methodology where only what is accessible to other classes should be revealed.
Please refer appendix 1for more details on documentation using javadoc
6.1 Beginning Comments
Following should be incorporated just at the beginning of the java file
i.
Author:
ii.
File Name
iii.
Created Date:
The General Declaration section of the code should have the following details in the given format.
/**
* File Name
*
* @author
*
* File created on: MMM DD, YYYY
*
*/
References
QSD/REF/919
Ver. Rev. 9.01
7 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
Example:
/**
* CriteriaMultiController.java
*
* @author Infosys
*
* File created on: Apr 16, 2008
*
*/
6.2 Comments for a Class
Following should be incorporated just above the class definition
i.
Author:
ii.
Class Name
The General Declaration section of the code should have the following details in the given format.
/**
* Class Name
*
* @author
*
*/
Example:
/**
* CriteriaMultiController
*
* @author Infosys
*
*/
6.3 Comments for a Method
Just above a method explain the following
i.
Brief Description of the method
ii.
Explain return values
iii.
Parameters:
All parameters must have explanation.
The functionality of each method in the code must be written in the given format at the beginning of the method.
/**
* Description
* @param
* @return
*/
Example:
/**
* Display Criteria List.
* @param request
* @param response
* @return
*/
References
QSD/REF/919
Ver. Rev. 9.01
8 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
6.4 Single Line Comments
Use the ‘//’ comment delimiter to put in single line comments. A blank line should precede a single line
comment. The format is given below.
<Your code>
<Blank line>
// Your comment
<Your code>
Eg.
iCount = iCount + 1;
//Checking if iCount is less than max count
if (iCount == I_MAX)
{
…
}
6.5 Block Comments
A block comment should be preceded by a blank line to set it apart from the rest of the code. Block
comments should be formatted as follows
/*
* This is a block comment
*/
It is a general practice to highlight the comment inside the source file as shown above. Since javadoc
treats the first line as /** followed by many asterisks (NOT /* followed by asterisks), this box structure is
treated as a documentation comment. This will appear in the javadoc output and will result in very bad
user documentation. AVOID USING “BOX” - ING for multi-line comments.
6.6 End of Line Comments
Use the //comment delimiter to put in comments at the end of a line. This should not be used to comment
out multiple lines of code.
7. CODING STYLE
The style followed must be readable. Be consistent. The same style has to be followed through out the
class and application. Here are two different styles of coding
void
}
vectMyFn (...){
and
void vectMyFn (...)
{
}
Both the styles are can be used, but be consistent.
Whatever the convention is followed, the code must be aligned properly. Use the same tab size for all the
files.
7.1 Indentation
Line indentation is always 4 spaces, for all indentation levels.
References
QSD/REF/919
Ver. Rev. 9.01
9 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
The construction of the indentation may include tabs as well as spaces in order to reduce the file size; however,
you may not change the hard tab settings to accomplish this. Hard tabs must be set every 8 spaces
Note: If this rule was not followed, tabs could not be used because they would lack a well-defined meaning.
7.2 Wrapping Lines
When an expression will not fit on a single line, break it according to these general principles
 Break after a comma
 Break before an operator
 Align the new line with the beginning of the expression at the same level on the previous line
 If the above rules lead to confusing code, just indent 8 spaces instead.
Eg.
Method1(longExpression1, longExpression2, longExpression3,
LongExpression4, longExpression5);
Var2 = longName1 + longName2 – longName3 * (longName4
+ LongName5)
7.3 Try-catch-finally
Each block should start in a new line and the opening brace should be there in the starting line of the block
itself.
Eg.
try
{
. . . .
}
catch (arg0 e0)
{
. . . .
}
catch (arg1 e1)
{
. . . .
}
finally
{
. . . .
}
8. BEST PRACTICES
8.1 Exceptions
We should almost never be writing functions that declare themselves to throw Exception. This makes it
very difficult to code to an API and handle Exceptions gracefully. Throw the particular Exception subclass that is appropriate to your code—either one of the pre-existing java Exceptions or your own.
8.2 Catch() Statement
Here are some Best Practices for your catch statements.
In general, no one should catch( Throwable ). Throwable has 2 sub-classes, Error and Exception. Errors
are Really Bad Things that often indicate VM-wide problems, such as OutOfMemoryError. Generally
speaking, no one wants to catch these in their applications. If you catch( Throwable ) and the Throwable is
an instanceof ThreadDeath and you don’t re-throw it, the Thread isn’t killed and Bad Things Happen.
In general, there is no reason to catch( Exception ). There are 2 types of Exceptions that can be thrown in
any try block: checked Exceptions and unchecked Exceptions. Checked Exceptions: These are the
References
QSD/REF/919
Ver. Rev. 9.01
10 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
Exceptions declared in the throws clauses of the methods called in the try block. Because these Exceptions
are declared, you know the types of Exceptions that can be thrown. The specific Exceptions you are after
can each be caught independently.
The unchecked Exceptions are all sub-classes of RuntimeException. If you want to handle these, just
catch( RuntimeException ). If you want to handle one or two specific RuntimeExceptions (the common
one seems to be NullPointerException) just catch and handle that.
The avoidance of catch( Exception ) is more of a guideline. If, for example, you are going to catch a halfdozen different kinds of Exceptions and handle them all the same way, catch( Exception ) may make for
cleaner code. Just be sure you are not masking problems when you do so.
try
{
Eg.
whatever();
}
catch( FooException fooexc )
{
// Do nothing
}
catch( BarException barexc )
{
handleBar( barexc );
}
8.3 Empty Catch Blocks()
There should be no empty catch blocks, all exceptions should at minimum be logged
In the following piece of code,
try
{
// whatever
}
catch( Exception exc )
{
// logging code
}
Eg.
8.4 Logging
Usually all exceptions, errors and anomalous conditions of concern - in short any message that need
attention - needs to be logged.

log4j is to be used for logging.
There are five levels of logging: FATAL, ERROR, WARN, INFO, and DEBUG. Messages should be
logged using an appropriate logging level as described below:
 The DEBUG priority designates fine-grained informational events that are most useful to debug an
application. DEBUG messages should also be added for method entry and exit from any nontrivial methods.
 The INFO level designates informational messages that highlight the progress of the application at
coarse-grained level. INFO messages should pertain to information that would be useful at a very
high level. Since these messages typically will be logged in the production environment, INFO
messages should be used sparingly. One example of an INFO message is that a user logged into
the system.
 The WARN level designates potentially harmful situations.
 The ERROR level designates error events that might still allow the application to continue
running.
References
QSD/REF/919
Ver. Rev. 9.01
11 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited

The FATAL level designates very severe error events that will presumably lead the application to
abort.
Note : DEBUG will be turned off in production. INFO should be used only when you need to print
essential information in the logs.
Always use ERROR for logging any Error messages and stack traces.
8.5 String vs StringBuffers
Instead of:
String strBig = “somestring”;
strBig += computeSomeOtherString();
strBig += “this”;
strBig += yetAnotherString();
try
String strBig = new StringBuffer( “somestring” ).append(
computeSomeOtherString()).append( “this” ).append(
yetAnotherString()).toString();
You’ll be amazed how much faster your code runs if you are manipulating lots of strings.
8.6 JDBC Statement
If you use JDBC anywhere in your code, make sure you read & follow the procedures below.
Utilize Connection Pooling Techniques : Any connection opened must be closed. If connections are not
closed they will not be released back to the database or to the connection pool. Use a connection pooling
framework provided by Apache or your Appserver and don’t open and manage connections in your code.
Be diligent about closing all JDBC objects : Connections,ResultSets,Statements etc should always be
closed to avoid “Too many Open Cursors” error in the database.
Use the “Finally” block to close all the JDBC objects
This is very important
Separate JDBC Code from Business Logic. : Use a DataAccess framework or if not possible , create a
simple Utility for all DB related activities. Do no speard the JDBC code everywhere in your classes !
Consider query fetch size for large result sets. : ResultSets are open cursors . They cannot be serialized or
stored. Specify the size of retrieval when you are retrieving large resultsets.
Do not prepare Statements in a loop. If the statement needs to be executed in the loop, prepare it outside of
the loop and parameterize and execute it inside the loop.
Close all the statements before next use and after the last use.
8.7 Boolean Objects
There is no need for having a java.lang.Boolean objects. There can only be 2 values for such objects, and
they exist as static objects in the VM—Boolean.TRUE and Boolean.FALSE. It is recommended to use
them.
8.8 Synchronized(this)
If you have an entire method that needs to be called synchronously, the best way to guarantee that is with
this syntax:
Eg.
References
QSD/REF/919
class Good
{
Ver. Rev. 9.01
12 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
public synchronized void someMethod()
{
// whatever
}
}
This syntax is basically shorthand for:
Eg.
class OverlyIndented
{
public void someMethod()
{
synchronized( this )
{
// whatever
}
}
}
Classes OverlyIndented and Good do the same thing & have the same synchronization, but class
OverlyIndented is overly indented.
Note that synchronization should be done as locally as possible to where it is needed and should not be
required of API users. Thus, this syntax is wrong:
Eg.
class Bad
{
/**
* Usage: abcd. Calls must be synchronized.
*/
public void someMethod()
{
// whatever
}
}
Bad bad = new Bad();
synchronized( bad )
{
bad.someMethod();
}
.
The problem with the Bad class is that it requires users of the API to know that synchronization is
necessary. Instead, use the syntax as in the Good class below. However, note that, under some
circumstances code like this may be correct:
Eg.
class Good
{
public synchronized void goodMethod()
{
// whatever
}
public synchronized void betterMethod()
{
// whatever
}
References
QSD/REF/919
Ver. Rev. 9.01
13 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
public synchronized void bestMethod()
{
// whatever
}
}
Good good = new Good();
synchronized( good )
{
good.goodMethod();
good.betterMethod();
good.bestMethod();
}
8.9 Iterations
There are a number of pieces of code where developers need to iterate through lists, vectors. Before JDK
1.5, we often use:
List list = someList;
Iterator iterator = someList.iterator();
while(iterator.hasNext())
{
Iterator.next();
}
In JDK 1.5 and above, we use:
List list = someList;
for(ListItem item : someList)
{
Item…;
}
9. SIZE
9.1 Class Size
The number of non-static methods should not exceed 20 for a Key class but on an average should be
around 12. The number of non-static methods should not exceed 40 for a UserInterface class but on an
average should be around 25.
The number of static methods should not exceed 4 for a class;
Multiple classes of this size are more desirable and enable efficient debugging when compared to large
classes. By following an object-oriented approach this should be implemented.
9.2 Method Size
The size of a method ideally should not cross 20 to 25 statements; the number of method calls within a
method should not exceed 7 to 9.
10. DECLARATIONS
10.1 Number Per Line
One declaration per line is recommended since it encourages commenting.
References
QSD/REF/919
Ver. Rev. 9.01
14 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
String personName ;
//Name of Person
String participantType; // Type of Participant
Eg.
10.1.1 Placement
Put declarations only at the beginning of blocks. Don’t wait to declare variables before their first use; it can
lead to confusion
10.2 Initialising Variables
Java initializes the standard data type variables (int, char, boolean, float etc) that are declared outside
methods. But all classes that have the Object class to be the parent are initialized to null. So care must be
taken to initialize these variables first. For example when an instance of a String, or instance of a Vector or
Hashtable are used. They must be initialized.
String strName= new String();
Eg.
11. PACKAGES
All classes of an application should belong to at least one package.
12. PROGRAMMING PRACTICES
12.1 Providing Access to Instance and Class Variables
Don’t make any instance or class variable public without good reason. Often, instance variables don’t need
to be explicitly set or gotten—often that happens as a side effect of method calls.
One example of appropriate public instance variables is the case where the class is essentially a data
structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java
supported struct), then it’s appropriate to make the class’s instance variables public.
12.2 Access Specifies for a class
Classes can be friendly (default), protected or public as the need may be· Use private if the method is
accessible only within the class· Use friendly if the method is accessible only within the class and other
classes within the same package· Use protected if the method is accessible only within the class, other
classes within the same package and sub classes in different packages· Use public only if the method can
be called from any class in any package.
12.3 Referring to Class Variables and Methods
Avoid using an object to access static variables or methods. Use the class name instead.
Eg.
classMethod(); //OK
AClass.classMethod(); //OK
anObject.classMethod(); //AVOID!
12.4 Constants
Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a
for loop as counter values.
12.5 Variable Assignments
Avoid assigning several variables to the same value in a single statement. It is hard to read.
References
QSD/REF/919
Ver. Rev. 9.01
15 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
Eg.
fooBar.fChar = barFoo.lchar = 'c'; // AVOID!
Do not use the assignment operator in a place where it can be easily confused with the equalityoperator.
Eg.
if (c++ = d++) // AVOID! Java disallows
{
...
}
should be written as
if ((c++ = d++) != 0)
{
...
}
Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the
compiler, and besides, it rarely actually helps.
Eg.
d = (a = b + c) + r; // AVOID!
should be written as
a = b + c;
d = a + r;
12.6 Null checks
There should be null checks before you call any operation on a object
Eg.
myArrayList = dao.getDataList()
If (myArrayList != null )
{
…… Do the operation
Ex – myArrayList.size();
- myArrayList.getXYZ();
}
12.7 String comparison
Please use following order while doing string comparison
If ( “STRING_CONSTANT”.equals(dto.getPlanName())
{
// do something
}
Do not attempt to compare strings using code as:
If( “STRING_CONSTANT” == dto.getPlanName())
{
// do something
}
12.8 Object instantiation
If you have a for loop, to iterate on the list, define the object reference outside the loop and assign the new
reference to same variable in for loop
Eg.
References
QSD/REF/919
Object obj = null;
for ( int i=0; i < araylist.size(); i++ )
{
obj = (Object)arrylist.get(i);
}
Ver. Rev. 9.01
16 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
Do not instantiate object if it is not necessary in declaration
Eg.
MyObject myObject = new MyObject();
myObject = dao.getObject();
In above code first object instantiation is unnecessary as the dao method will return you an object of type
MyObject. However, null checking is a must before invoking any method on an object where the state of
the object is undeterminable, in other words when the object creation scope is outside of your class logic.
12.9 Unnecessary method calls
In case where you have a for loop for traversing on an arraylist containing dto’s, most people have code
like:
Eg.
Arraylist al = proxy.getPlans(xyz);
for ( int i=0; i < al.size() ; i++ )
{
obj = (Object)al.get(i)
}
The code above leads to the invocation of size() method on the arraylist evertime the loop is executed.
This code can be re-written as:
Eg.
Arraylist al = proxy.getPlans(xyz);
If(al != null)
{
int size = al.size();
for ( int i=0; i <size ; i++ )
{
obj = (Object)al.get(i)
}
}
However, this should not be done in case the ArrayList object is being altered inside the loop as the size
obtained earlier will be incorrect.
12.10 Exception handling
Try/ catch blocks will be added in all methods where exceptions can be expected due to data operations
within the method or other method involcations. The exceptions that are caught NullPointerException/
ArrayIndexOutOfBoundsException/ SQLException in the DAO/ Impl/ Proxy layers will be wrapped into
the module-specific exception object and propagated downsteam i.e. towards the calling class. The
exception object will be populated with the error code corresponding to the technical or business exception
encountered.
Eg.
Method Call Sequence
Action -> Proxy -> Impl -> DAO
Exception Throwing sequence
DAO (catch exception and throws to) -> Impl (catch….)-> Proxy (catch..) -> Action
Based on the error code the Action class will decide on whether an error message needs to be displayed to
the user and will map the error code to the corresponding error message.
No blank catch blocks should be present in the code. All the exceptions should be logged into the
application log files via the eCI Logging statement and the printStackTrace() method of the Exception
class.
References
QSD/REF/919
Ver. Rev. 9.01
17 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
12.11 Commented code blocks
There should be no commented code blocks in the java source files. This is often caused by copying code
blocks from existing source files as a reference. As a part of this the comments from the source class also
get copied over.
12.12 System.out.println ()
No System.out.println() statements should be present in the java source files. The statements that were
added during the initial development phase have to now be replaced with the appropriate eCI Logging
statements (Error/ Warning/ Debug/ Info). There should be no commented System.out.println()
statements either.
13. MISCELLANEOUS
13.1 Import of Classes
Import only the classes that are required from a package. Import the entire package only when a large
number of classes from that package are going to be used.
13.2 Multiple decisions
In Java the switch - case statement can handle only chars, bytes and ints. Under this circumstance it may be
required to write nested If statements. In this case when testing multiple decisions, check the most
commonly occurring first. Restrict nested If’s to three levels by using the fall through logic.
13.3 Error Messages

Error Message should be raised properly wherever necessary.

Error messages used should be clear and consistent

Error messages should not blame the user and should not be technical. The technical errors
be logged into a specific location.

Exceptions should be handled specifically rather than generally.
can
Catch (NumberFormatException e)
{
}
Instead of just
Catch (Exception e)
{
}

Error/Information messages must be stored in a property file and then accessed to display
whenever necessary.

It is recommended to have a logging utility to log all the errors in a common place (eg: database
table or a file in the SilverStream server) which will be helpful in case of any exceptions.

Use exception.getmessage () while logging exceptions, instead of hardcoding your own log
messages.
References
QSD/REF/919
Ver. Rev. 9.01
18 of 19
Infosys
Java Coding Standards
© Infosys Technologies Limited
13.4 Performance related

Re-usable objects are to be created as static objects in code, in order to avoid instantiating it
multiple times, which will have an impact on performance.
For e.g. the logger object could be created once at the server level and the same object could be reused.

File read operations must be restricted to a minimum. Instead of reading different parameters
from the same parameter file again and again, it is better to load the entire property file into
memory once and read its contents from the memory thereafter.

Stringbuffers to be used instead of Strings when large string values are assigned to the
variables.

Objects should be reused after a cleanup instead of reinstantiation.

If possible declare the classes as final.

Synchronize should never be used on private methods since private methods are generally invoked
by public methods resulting in unnecessary overhead.

Use ArrayList instead of Vector and HashMap/TreeMap instead of Hastable. ArrayList and
HashMaps don’t have synchronized methods like their counterparts Vector and Hashtable, thereby
enhancing performance.
References
QSD/REF/919
Ver. Rev. 9.01
19 of 19
Download