Standards


1.    Objective


The objective of this document is to address the coding standard and guidelines required for packages written in Java

Here are the few advantages when we are following the coding standard and guidelines.

·         Easy Maintenance
·         Easy Code Integration / Deployment
·         Uniform Problem Solving approach
·         Minimizes Communication
·         Prevent Repeating Occurrence of Particular Problem
·         Minimizes Performance Pitfalls
·         Ensure Quality Product
·         Saves Money Due to Less Man Hours
·         Apply the required Basic Security (Refer Security Section)
Easy Maintenance
The source code will be more comprehensive and will become easy-to-maintain. As the programmers became more and more familiar with the coding style as they implement the coding standards on project after project.
Easy Code Integration/ Deployment
Prevent integration problems during merging all developer working copies to a master copy several times a day for deployment.
Uniform Problem Solving Approach
The uniform approach for solving problems will be handy because the code standards documents reveal the recommended methods that were tried and tested on the earlier projects.
Minimizes Communication
Less communication between developers and managers will be needed because the programmers will not asked anymore on the details of the specification document because the defaults are all stated in coding standards.



Prevent Repeating Occurrence of Particular Problem
It is common to the less experience programmer to re-invent the wheel. When there are coding standards, there is a big chance that particular problem is not really a new problem, but in fact, a solution may be documented before.
Minimizes Performance Pitfalls
Repeated performance pitfalls could be avoided. It is a common case that a released software product could be less impressive when it comes to performance when the real data has been loaded in the new developed database application.

Ensure Quality Product
·         Well documented coding standards will aid the creation of "Test Scripts". Having reviewed the source code and tested an application based on compliance to coding standards, it added strong direction to ensure quality of the software product

·         Because code standards implement traceability, the item ids can be used to describe a violation in the "Test Results" document that both developers and testers are familiar with

·         It is important for the project managers to maintain and secure source code quality on their projects by implementing coding standards

It is also beneficial for the organization who are applying for ISO 9001 license because coding standards is a complement from organization's execution plan requirements

Saves Money Due to Less Man Hours
Lesser man-hour consumption as the sum of all efforts implementing coding standards.


2.    Naming Conventions

1)   Package Names

Package name should be in all lower case. The initial package name representing the domain name must be in lower case.

Whenever possible, any package name should include the lower-case domain name of the originating organization.

Example:
package com.company.application.modulename;
package com.google.ads.controller;

2)   File Names

The Java files must have .java extension.
Java source file names are of the form: Class or InterfaceName.java
Where Class or InterfaceName is exactly the name of the public class or interface defined in the source file.

Java Files uses the following Type Suffix:
Java source .java
Java bytecode .class

3)   File Encoding

Source files are encoded in UTF-8.

4)   File Structure

       Source file consists of, in order:
·   License or copyright information of the organization, if present
·   Package statement
·   Import statements
·   Exactly one top-level class
·   Exactly one blank line separates each section that is present

5)   Special Characters

Whitespace Characters
Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that:
·         All other whitespace characters in string and character literals are escaped
·         Use TAB for indentation, don’t use Space or Tab characters for indentation
Special Escape Sequences
For any character that has a special escape sequence (\b, \t, \n, \f, \r, \", \' and \\), that sequence is used rather than the corresponding octal (e.g. \012) or Unicode (e.g. \u000a) escape.

Non-ASCII Characters
For the remaining non-ASCII characters, either the actual Unicode character (e.g. ∞) or the equivalent Unicode escape (e.g. \u221e) is used, depending only on which makes the code easier to read and understand.

Example
Discussion
String unitAbbrev = "μs";
Best: perfectly clear even without a comment.
String unitAbbrev = "\u03bcs"; // "μs"
Allowed, but there's no reason to do this.
String unitAbbrev = "\u03bcs"; // Greek letter mu, "s"
Allowed, but awkward and prone to mistakes.
String unitAbbrev = "\u03bcs";
Poor: the reader has no idea what this is.
return '\ufeff' + content; // byte order mark
Good: use escapes for non-printable characters, and comment if necessary.

6)   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/PascalCase 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;
Examples: Searchable, Sortable, Network Accessible. Otherwise use nouns or noun phrases.

Example:

// GOOD type names:
LayoutManager, AWTException, ArrayIndexOutOfBoundsException

// BAD type names:
ManageLayout // verb phrase
awtException // first letter lower-case
array_index_out_of_bounds_exception // underscores

7)   Field Names

Names of non-constant fields (reference types, or non-final primitive types) should use the infixCaps/camelCase 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.

Example:

boolean isResizable;
char recordDelimiter;

Names of fields being used as constants should be all upper-case, with underscores separating words.

Example:

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:

Example:

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.

8)   Constants

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.

              Example:
                
                 final int LOGIN_SUCCESS = 1;
Associated constants (final variables) should be prefixed by a common type   name.
        
            Example:

             final int COLOR_RED = 1;
final int COLOR_GREEN = 2;
final int COLOR_BLUE = 3;
public static final String CONSTANT_STRING= “STRING_VALUE”;
public static final boolean PASS = true;
public static final boolean FAIL = false;
public static final String EMPTY_STRING = "";
public static final int NOT_FOUND = -1;

Note: There are instances where interfaces are used just to keep constants though we don't see any reason to do that and is also considered a bad practice to create an interface to hold constants; another approach is to keep it in the class where it makes more sense.

9)   Method Names

Method names should use the infixCaps/camelCase 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.

Methods should be verbs, in mixed case with the first letter lowercase and with the first letter of each internal word capitalized

Example:

   // GOOD method names:
   showStatus(), drawCircle(), addLayoutComponent(), run();

   // BAD method names:
   mouseButton() // noun phrase; doesn’t describe function
   DrawCircle() // starts with upper-case letter
   add_layout_component() // underscores

10)        Arrays

Arrays should always be specified using the form below and the maximum length of the array name is 30 characters.

An array type is written as the name of an element type followed by some number of empty pairs of square brackets []. The number of bracket pairs indicates the depth of array nesting. Every array type implements the interfaces Cloneable and Serializable.
Example:

<data type>[][]…[] arrayname;
Declarations of Array variables:

                      int [] companyNames;             //array of int
double [][] salary;                    //array of array of double

       The form given below must NOT be used:
           
Example:   

int myArray [];  //WRONG USAGE!

Note: All array accesses are checked at run time, an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.

11)        List Maps

Example:
 
List<String> sampleList = new ArrayList<String>;
Map<Integer, String> sampleMap = new HashMap<Integer, String>;

Use an Array instead of an ArrayList if the size can be fixed:
If you can determine the number of elements, use an Array instead of an ArrayList, because it is much faster. An array also provides type checking so there is no need to cast the result when looking up an object.

Use an ArrayList or LinkedList to hold a List of objects in a particular sequence:
A List holds a sequence of objects in a particular order based on some numerical indexes. It will be automatically resized. In general, use an ArrayList if there are many random accesses. Use a LinkedList if there are many insertions and deletions in the middle of the list.

Use HashMap or TreeMap To Hold Associated Pairs of Objects:
Use a HashMap if the objects do not need to be stored in sorted order. Use TreeMap if the objects are to be in sorted order. Since a TreeMap has to keep the objects in order, it is usually slower than a HashMap.

Replace Hashtable, Vector, and Stack:

- Replace a Vector with an ArrayList or a LinkedList.
- Replace a Stack with a LinkedList.
- Replace a Hashtable with a HashMap or a TreeMap.
- Vector, Stack, and Hashtable are synchronized-views of List and Map.

     For example, you can create the equivalent of a Hashtable using:

private Map hashtable = Collections.synchronizedMap (new HashMap());

However, bear in mind that even though methods in these synchronized-views are thread-safe, iterations through these views are not safe. Therefore, they must be protected by a synchronized block. 

12)        Abbreviations and Acronyms

Example:
exportHTMLSource();     // NOT: exportHtmlSource();
                openDVDPlayer();          // NOT: openDvdPlayer();
Avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).

         Note: Try to avoid using two or more abbreviations in one field or class name.


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

Example:
computeAverage();                    // NOT: compAvg();
ActionEvent event;                     // NOT: ActionEvent e;

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

15)        One Statement per Line

Each statement is followed by a line-break.

16)        Column Limit

Projects are free to choose a column limit of 80 characters. Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in the section Wrapping Lines.

17)        Exceptions

Lines where obeying the column limit is not possible (for example, a long URL in Javadoc, or a long JSNI method reference).
package and import statements.
Command lines in a comment that may be cut-and-pasted into a shell.

3.File Organization


A file consists of sections that should be separated by blank lines and optional comments identifying each section.

Files longer than 2000 lines are cumbersome and should be avoided.

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/ (or) 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

1)   Package and Import Statement

The package statement must be the first statement of the file. All related files should belong to a specific package. Ensure that package names are all lowercase with no underscores

Example:

     package com.company.application.modulename;

 Imported classes should always be listed explicitly.

Good Practice:                           Bad practice:
import java.util.List;                           // NOT: import java.util.*;
import java.util.ArrayList;
         import java.util.HashSet;

Note: Import statements should be grouped together by package name. A single blank line may be used to separate groups of import statements.

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

3)   Methods

Methods Modifiers should be given in the following order;
<access> static abstract synchronized <unusual> final native
The <access> modifier (if present) must be the first modifier.
Example:
             public static double square(double a);  // NOT: static public double square(double a);


4)   Types

Type conversions must always be done explicitly. Never rely on implicit type conversion.
Example:
            floatValue = (float) intValue;    // NOT: floatValue = intValue;
Array specifiers must be attached to the type not the variable.
Example:
int[] a = new int[20];               // NOT: int a[] = new int[20]

5)   Variables

·         Local 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 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
Example:
double[] vertex;                       // NOT: double vertex[];
int[] count;                              // NOT: int count[];

public static void main(String[] arguments)
public double[] computeVertex()

6)   Loops

Only loop control statements must be included in the for() construction.
Example:
          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

7)   Conditionals

The conditional should be put on a separate line.
Example:
            if (isDone)  {                 // NOT: if (isDone) doCleanup();
doCleanup();
            }

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.

Example:
              
private static final int TEAM_SIZE = 11;
Player[] players = new Player[TEAM_SIZE];
// NOT: Player[] players = new Player[11];

if (teamSize = TEAM_SIZE )  {   // NOT: if (teamSize = 11) doCleanup();
doCleanup();
            }

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.

Example:

                        double total = 0.0;                   // NOT: double total = 0;
double speed = 3.0e8;             // NOT: double speed = 3e8;
            double sum;
            sum = (a + b) * 10.0;

Floating point constants should always be written with a digit before the decimal point.

Example:

double total = 0.5;                   // NOT: double total = .5;

5.    Layout


The class and interface declarations should have the following form:

Example:

class Rectangle extends Shape implements Cloneable, Serializable
{
   ...
}

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 also recommended.

Method definitions should have the following form:

Example:

public void someMethod() throws SomeException
{
     ...
}

Class and Interface Declarations:

When coding Java classes and interfaces, the following formatting rules should be followed:

·         No space between a method name and the parenthesis “(“ starting its parameter list

·         Open brace “{” appears at the end of the same line as the declaration statement

·         Closing brace “}” starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the “}” should appear immediately after the “{“

Example:

class Sample extends Object {
                 int ivar1;
int ivar2;

            Sample(int i, int j) {
                        ivar1 = i;
                             ivar2 = j;
                 }

                 int emptyMethod() {}
                 ...
}

Methods are separated by a blank line




·         Operator should be surrounded by a space character

·         Java reserved words should be separated by a space

·         Commas should be followed by a character then blank space should be appeared after comma

·         Colon should be surrounded by a space character

·         Semicolon in for statement should be followed by a white space between the expressions

Example:

            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. There should be one and only one single blank line between each method inside the class.

Example:

                  // 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 a rotation transformation
matrix.setElement(1, 1, cosAngle);
matrix.setElement(1, 2, sinAngle);
matrix.setElement(2, 1, -sinAngle);
matrix.setElement(2, 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 for more details on documentation using javadoc

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: DD-MMM-YYYY
 *
 */
           
Example:
/**
 * CriteriaMultiController.java
 *
 * @author CompanyName
 *
 * File created on: 04-APR-2015
 *
 */

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 CompanyName
 *
 */

3)   Comments for a Methods

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

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>

     Example:
    
                 iCount = iCount + 1;
//Checking if iCount is less than max count
if (iCount == I_MAX) {

}

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

1)   Indentation

Line indentation is always 4 spaces, for all indentation levels.
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.

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

Example:

Method1(longExpression1, longExpression2, longExpression3,
               LongExpression4, longExpression5);
Var2 = longName1 + longName2 – longName3 * (longName4
       + LongName5)

function(longExpression1, longExpression2, longExpression3,
        longExpression4, longExpression5);

var = function1(longExpression1,
                   function2(longExpression2,
                                longExpression3));

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.

Example:
                
try {

                                                 . . . .
                                    }
catch (ExceptionClass e0) {

                                            . . . .
                                    }
catch (ExceptionClass e1) {

                                                . . . .
                                    }
finally {

                                                . . . .
                        }       


8.    Best Practices

1)   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 not spread 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.

2)   File Handling

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

3)   Exception Handling

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 sub-class that is appropriate to your code—either one of the pre-existing java Exceptions or your own.

User Try/ catch blocks in all methods where exceptions can be expected due to data operations within the method or other method invocations. 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.
Example:
                
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 Logging statement and the printStackTrace() method of the Exception class.

4)   Empty Catch Blocks()

There should be no empty catch blocks, all exceptions should at minimum be logged, In the following piece of code,

Example:
      
   try {
                   // whatever
}
catch( Exception exc ) {
// logging code
}

5)   Catch() Statement

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 instance of 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 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 half-dozen 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.
   Example:
                
try {
whatever();
}
catch( FooException fooexc ) {

            // Do nothing
}
catch( BarException barexc ) {

handleBar( barexc );
}

6)   Multi-Catch

In this feature, we can catch multiple exceptions in single catch block. Before java 7, restricted to catch only one. To specify the list of expected exceptions a pipe (‘|’) character is used.
            Example:

try {
statements;
}
catch (ClassNotFoundException | IllegalAccessException ex) {
thorw ex;
}

7)   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 can be logged into a specific location

·         Exceptions should be handled specifically rather than generally
                      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

8)   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 non-trivial methods

·         The INFO level designates informational messages that highlight the progress of the application at every 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

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

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

10)        String vs StringBuffers

Stringbuffers to be used instead of Strings when large string values are assigned to the variables.
Example:

String strBig = new StringBuffer( “somestring” ).append(
computeSomeOtherString()).append( “this” ).append(
yetAnotherString()).toString();
Instead of:
String strBig = “somestring”;
strBig += computeSomeOtherString();
strBig += “this”;
strBig += yetAnotherString();

Note: In the case of non-multi threaded environment, always prefer StringBuilder rather StringBuffer to improve the performance of the application.

You’ll be amazed how much faster your code runs if you are manipulating lots of strings.

11)        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())  { //NOT:

// do something
}

12)        ArrayList

Use ArrayList instead of Vector, HashMap/TreeMap instead of Hastable. ArrayList and HashMaps don’t have synchronized methods like their counterparts Vector and Hashtable, thereby enhancing performance.

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

14)        Iterations

There are a number of pieces of code where developers need to iterate through lists, vectors.

Example:

Before JDK 1.5, we often use as below:

List list = someList;
Iterator iterator = someList.iterator();

while(iterator.hasNext()) {

            Iterator.next();
}

In JDK 1.5 and above, we use generics as below:

List <T> list = someList;
for(<T> item : someList) {

            Item…;
}

15)        Class

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; If possible, declare the classes as final.

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.

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

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.

16)        Object

Object Instantiation

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 re-used.

Objects should be reused after a cleanup instead of re-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

Example:

Object obj = null;
for ( int i=0; i < araylist.size(); i++ ) {
obj = (Object)arrylist.get(i);
}

Do not instantiate object if it is not necessary in declaration

Example:

            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.

Null Checks

There should be null checks before you call any operation on an object

Example:

            myArrayList = dao.getDataList()
If (myArrayList != null ) {

…… Do the operation
Ex – myArrayList.size();
- myArrayList.getXYZ();
}

17)        Method

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.

Avoid using an object to access static methods. Use the class name instead.

Example:

classMethod(); //OK
AClass.classMethod(); //OK
anObject.classMethod(); //AVOID!

Unnecessary Method Calls

In case where you have a for loop for traversing on an arraylist containing dto’s (data transfer objects), most people have code like:

Example:

            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:

Example:

            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.

18)        Synchronized(this)

If you have an entire method that needs to be called synchronously, the best way to guarantee that is with this syntax:

Example:

class Good {
                        public synchronized void someMethod() {
                                     // whatever
                       
}
      }
This syntax is basically shorthand for:

Example:

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

Example:

class Good {

                        public synchronized void goodMethod() {
                       
                                    // whatever
                        }

                        public synchronized void betterMethod() {
                       
                                    // whatever
                        }

                        public synchronized void bestMethod() {
                       
                                    // whatever
                        }
}

Good good = new Good();
synchronized( good ) {
    good.goodMethod();
    good.betterMethod();
    good.bestMethod();
}

Synchronize should never be used on private methods since private methods are generally invoked by public methods resulting in unnecessary overhead

19)        Variable

            Number Per Line

One declaration per line is recommended since it encourages commenting.

Example:

            String personName ;     //Name of Person
            String participantType; // Type of Participant

Placement

Put declarations only at the beginning of blocks. Don’t wait to declare variables before their first use; it can lead to confusion

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

Example:

            String strName= new String();

Accessing Class Static Variables

Avoid using an object to access static variables. Use the class name instead.

Example:

int minValue = AClass.MIN_VALUE; //OK

Constants

It should be all upper-case, with underscores separating words.

Example:

MIN_VALUE, MAX_BUFFER_SIZE, OPTIONS_FILE_NAME

Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values.

Variable Assignments

Avoid assigning several variables to the same value in a single statement. It is hard to read.

Example:
           
fooBar.fChar = barFoo.lchar = 'c'; // AVOID!

Do not use the assignment operator in a place where it can be easily confused with the equality operator.

Example:

            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.

Example:
           
d = (a = b + c) + r; // AVOID!

should be written as
a = b + c;
d = a + r;

20)        Commented Code Blocks

No commented code blocks should be present 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.

·         To remove/solve all warnings/errors message code if anything is there when you compile the application

21)        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 Logging statements (Error/ Warning/ Debug/ Info). There should be no commented System.out.println() statements either.

22)        Packages

All related classes of an application should belong to at least one package.


9.    Security


The Java Class Library provides a number of APIs related to security, such as standard cryptographic algorithms, authentication, and secure communication protocols(SSL).

The JVM is binary form of programs running on the Java platform is not native machine code but an intermediate bytecode. The JVM performs verification on this bytecode before running it to prevent the program from performing unsafe operations such as branching to incorrect locations, which may contain data rather than instructions. It also allows the JVM to enforce runtime constraints such as array bounds checking.

Java objects/data can be cryptographically signed using various cryptography algorithms. The data is stored as in java objects form and can be extra protected using various encryption algorithms so that the data is not easily extractable.

Java has an inbuild Security Manager, a security manager is an object that defines a security policy for an application. This policy specifies actions that are unsafe or sensitive. Any actions not allowed by the security policy cause a SecurityException to be thrown. An application can also query its security manager to discover which actions are allowed.

The various ways for security for web applications are:

·         Authentication and Authorization by using various frameworks like spring security, JWT, OAuth  etc

·         Using basic Http Authentication or Form based authentication

·         Form based validation to be also performed on API server side as the client may disable the script validation so server/API has to handle the validations

·         Use parameterized input with Type-Safe for dynamic SQL statements to prevent the SQL injection

·         API responses should be either JSON objects (not json strings) or XML

·         Use servlet filters to intercept the client requests

·         Audit logs to be recorded as physical file as well as stored in database for debugging/tracing/reporting. The logs retention period days should be configured in application configuration file based on this value, the days prior log files should be deleted from the system

·         Windows API errors to be logged to Windows Event Logs

·         Use Cryptographic protocols (SSL) for JAVA web APIs for supporting the TLS 1.2 AES with 256 bit encryption


10.EXAMPLE


The following example shows how to format a Java source file containing a single public class.

/*
 * Copyright (c) Company Name. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * Company. ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with.
 *
 */

package com.comapny.appname.modulename;

import java.util.xxxxx;

/**
 * Class description goes here.
 *
 * @version 1.10 28 July 2015
 * @author Firstname Lastname
 */
public class SomeClass {

 /** classVariable1 documentation comment */
 public static int classVariable1;

 /** classVariable2 documentation comment */
 private static Object classVariable2;

 /** instanceVariable1 documentation comment */
 public Object instanceVariable1;

 /** instanceVariable2 documentation comment */
 protected int instanceVariable2;

 /** instanceVariable3 documentation comment */
 private Object[] instanceVariable3;


 /**
 * ...method SomeClass documentation comment...
 */
 public SomeClass() {
 // ...implementation goes here...
 }

 /**
 * ...method doSomething documentation comment...
 */
 public void doSomething() {
 // ...implementation goes here...
 }

 /**
 * ...method doSomethingElse documentation comment...
 * @param someParam description
 */
 public void doSomethingElse(Object someParam) {
          // ...implementation goes here...
 }

}

No comments:

Post a Comment