Vous êtes sur la page 1sur 12

Java Code Review Check List

___________________________________________________

Version 1.0
2
1 Introduction
1.1 Purpose of the document

This document provides process guidelines that needs to be followed to adhere coding standards and
the steps followed for the end to end screen generation in Branch channel application.

1.2 Intended Audience


This document is intended for Branch Channel developers.

1.3 Scope

This document covers following areas:

1. General Java Coding standards


2. Screen generation using the tool.
3. Coding Standards followed need to be followed for Branch Channel Applicatiion development.

3
2 Introduction
2.1.1 Overview
Code must be formatted to agree coding standards. Coding standards keep the code consistent and easy
for the entire team to read and re-factor. Code that looks the same encourages collective ownership.

2.1.2 Clearer Understanding


Whether you are amending an existing program or writing something new, clearly structured code that tells
you what kind of object you are dealing with and how it fits into the structure can do some of the thinking for
you.

2.1.3 Better Code


Simply using clear names for objects, and laying out code so that the structure is easy to follow, should
reduce spaghetti code and result in better-structured modules. It will be easier for others to see how the
code works, and therefore modify it as necessary without increasing code entropy, which occurs when the
originally intended design of a module is eroded by subsequent changes.

2.1.4 Fewer Decisions to make


Having guidelines to follow means that there are some decisions that you do not have to make. Naming
objects, for example, becomes simpler. You also do not have to justify, argue and defend every decision
you make.

2.1.5 Easier Maintenance


Maintenance programming becomes easier since the code is easier to predict, read and modify. Changes
are easier to implement and are more likely to work first time, making them faster and cheaper.

2.2 General Java Coding Standards


Java is a programming language expressly designed for use in the distributed environment of the
internet. Java can be used to create complete applications that may run on a single computer or be
distributed among servers and clients in a network. It can also be used to build a small application
module or applet for use as part of a web page.

2.2.1 Naming Conventions


Standard Java Naming Conventions needs to be followed by the programmer.

Identifier Comments Example

Package Lowercase alphabetical com.tcs.nbl


characters with dot for hierarchy

Class or Interface All Class names or Interface Timer, HttpServlet


names should start with a
capital letter. If there are
mutiple words in the class name
then each word must also begin
with a capital letter

Method or Field Method and Variable name must processTransaction


start with lowercase and if there

4
are multiple words in the name,
then you need to use Uppercase
for starting letters for the words
except for the starting word.
This is called as
lowerCamelCase

Constant Field One or more uppercase and MAX_VALUE


multiple words separated by
underscore character.

Local variable Same as membernames except i, xref, houseNumber


abbreviations are permitted for
well known conventions like i.

2.2.2 Class
 Context independence. All the dependency should be passed as part of the constructor. If a class is
context aware and tightly coupled, testing with mock or stub is not possible.
 Class size should not be more than 500 lines including comments. Reducing the class size ensures
easy maintenance and re-factoring of the code in future.

 Value objects should be immutable with properly overridden equals, hashCode and toString. The key
difference between value object and entity is unique identity using primary keys. Value objects are equal
if all the fields are identical in two instances. But entities are equal only if primary key is equal.

2.2.3 Method and Field

 Don't use return code. Instead use exceptions. Return type should be used to return computed values.
This will make method signature intention reveling instead of always returning int (status code) as return
value.
 Method size should not me more than 10 lines. For few exceptional cases, it can be longer with reviewer
approval but limited to max 25 lines. Reducing the class size ensures easy maintenance and re-
factoring of the code in future.
 Typically each private method does one and only one thing.

 Maximum number of parameters to method and constructor should be limited to four.

 Avoid duplication in methods by including another method.

 Minimize accessibility of members. Never make fields as public. Instead encapsulate and expose using
method.
 All public methods should have javadoc.

 Fields in Serializable objects are part of public API even when visibility is private. Make sure to add java
doc and add @serial annotation.

 Limit number of loops and conditional chaining (for, while, if/else & switch) to one in a method.

5
2.2.4 Conditions and Loops

 Use for-each loops instead of traditional for loops.

 When index access is required, initialize size one time instead of invoking size() method for each
iteration in typical loop. For arrays replace size() with length.
 Don't do nested loop or nested conditional chaining.

 Most of the times switch can be replaced with polymorphism using interface as type. Use switch only in
factory methods and module entry points.

 Don't concatenate Strings inside loops.

2.2.5 Exceptions and Error Handling

 Use exceptions instead of return code. Provide getter method in exception class to retrieve error code
and translate to message for logging and notification.
 Use exceptions only for exceptional conditions and not as a conditional construct.

 By default use RuntimeExceptions because most of the exceptions are not recoverable and typically
logged and notified. Do not use printStackTrace() to print the stack trace to console.
 An error should be detected and handled if it affects the execution of the rest of a routine. For example,
if a resource allocation fails, this affects the rest of the routine if it uses that resource. This should be
detected and proper action taken. In some cases, the 'proper action' may simply be to log the error.
 Consider notifying your caller when an error is detected. If the error might affect your caller, the caller
should be notified. For example, the 'Open' methods of 'a file class should return error conditions. Even
if the class stays in a valid state and other calls to the class will be handled properly, the caller might be
interested in doing some error handling of its own.
 Document all exceptions thrown by each method. Write test cases for all exceptions conditions.

 Don't ignore exceptions. Do not have empty catch blocks.

 Make sure to roll back during exception to avoid inconsistent state either in-memory or in persistent
store.
 Make sure all resources and memory allocated are released in the error paths.

2.2.6 Generics

 Don't use raw types in new code.

 Eliminate unchecked warnings from compiler. If you can't eliminate a warning, and you can prove that
the code that provoked the warning is typesafe, then suppress the warning with annotation
@SuppressWarning(“unchecked”).

2.2.7 Enums

 Use Enums instead of constants.

 Use two field enum instead of boolean (e.g. instead of isBlocked boolean use enum state {OPEN,
BLOCKED}. Enum is intention reveling.

6
2.2.8 Thread Safeness

 If global variables can be accessed by more than one thread, code altering the global variable should be
enclosed using a synchronization mechanism such as a mutex. Code accessing the variable should be
enclosed with the same mechanism.
 If some objects can be accessed by more than one thread, make sure member variables are protected
by synchronization mechanisms.
 It is important to release the locks in the same order they were acquired to avoid deadlock situations.
Check error code paths.

2.3 General JSP Coding Standards

2.3.1 Indentation
Indentations should be filled with space characters. Tab characters cause different interpretation in the spacing
of characters in different editors and should not be used for indentation inside a JSP page. Unless restricted by
particular integrated development environment (IDE) tools, a unit of indentation corresponds to 4 space
characters.

2.3.2 White Space


White space further enhances indentation by beautifying the JSP code to reduce comprehension and maintenance effort. In
particular, blank lines and spaces should be inserted at various locations in a JSP file where necessary.

2.3.3 Blank Spaces


A white space character (shown as   ) should be inserted between a JSP tag and its body. For instance, the
following
<%=
customer.getName()
%>

is preferred over
<%=customer.getName()%>

There should also be space characters separating JSP comment tags and comments:
<%--
-
a multi-line comment broken into pieces, each of which
-
occupying a single line.
--%>
<%--
a short comment
--%>

7
2.3.4 Comments

There are two types of comments in jsp:


Hidden Comments
A hidden comment does not appear in the generated output in the html.
This comment is visible only on the server side because it is removed during JSP page translation.
Example of hidden comment:
<%-- This is hidden comment --%>
Output Comments
An output comment appears in the generated output in the html.
Example of output comment:
<!-- This is output comment -->
One should avoid using Output Comments as it is rendered in the output jsp.

2.3.5 JSP Declarations


As per the Java code convention, declarations of variables of the same types should be on separate lines:

Not recommended Recommended

<%! private int x; %>


<%! private int x, y; %>
<%! private int y; %>

In general, JSP declarations for variables are discouraged as they lead to the use of the scripting language to
weave business logic and Java code into a JSP page which is designed for presentation purposes, and because of
the overhead of managing the scope of the variables.

2.3.6 JSP Scriptlets


Where possible, avoid JSP scriptlets whenever tag libraries provide equivalent functionality. This makes pages easier to read
and maintain, helps to separate business logic from presentation logic.
 JSP scriptlets should ideally be non-existent in the JSP page so that the JSP page is independent of the scripting
language, and business logic implementation within the JSP page is avoided.
 If not possible, use value objects (JavaBeans components) for carrying information to and from the server side, and
use JSP scriptlets for transforming value objects to client outputs.
 Use custom tags (tag handlers) whenever available for processing information on the server side.

2.3.7 JSP Expressions


JSP Expressions should be used just as sparingly as JSP Scriptlets.
However, JSP expressions have preference over equivalent JSP scriptlets which rely on the syntax of the underlying scripting
language.
For instance,
<%= x %>

8
is preferred over
<% out.print( x ); %>

2.3.8 JSP Page Directive(s)


A JSP page directive defines attributes associated with the JSP page at translation time. The JSP specification
does not impose a constraint on how many JSP page directives can be defined in the same page
Ex:
<%@ page session="false" %>
<%@ page import="java.util.*" %>
<%@ page errorPage="/common/errorPage.jsp" %>
An exception occurs when multiple Java packages need to be imported into the JSP pages, leading to a very
long import attribute:

In this scenario, breaking up this page directive like the following is preferred:
<%-- all attributes except import ones --%>
<%@ page
...
%>
<%-- import attributes start here --%>
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>

2.3.9 Optional Tag Library Directive(s)


A tag library directive declares custom tag libraries used by the JSP page. A short directive is declared in a
single line. Multiple tag library directives are stacked together in the same location within the JSP page's body:
<%@ taglib uri="URI1" prefix="tagPrefix1" %>
<%@ taglib uri="URI2" prefix="tagPrefix2" %>
...

Just as with the page directive, if the length of a tag library directive exceeds the normal width of a JSP page (80
characters), the directive is broken into multiple lines:
<%@ taglib
uri="URI2"
prefix="tagPrefix2"
%>

Only tag libraries that are being used in a page should be imported.

2.3.10 Optional JSP Declaration(s)


JSP declarations declare methods and variables owned by a JSP page. These methods and variables are no
different from declarations in the Java programming language, and therefore the relevant code conventions
should be followed. Declarations are preferred to be contained in a single < %! ... %> JSP declaration block, to
centralize declarations within one area of the JSP page's body. Here is an example:

9
Disparate declaration blocks Preferred declaration block

<%! private int hitCount; %> <%!


<%! private Date today; %> private int hitCount;
... private Date today;
<%! public int getHitCount() {
return hitCount; public int getHitCount() {
} return hitCount;
%> } %>

2.3.11 Programming Practices


In general, avoid writing Java code (declarations, scriptlets and expressions) in your JSP pages, for the following
reasons:
 Syntax errors in Java code in a JSP page are not detected until the page is deployed. Syntax errors in tag
libraries and servlets, on the other hand, are detected prior to deployment.
 Java code in JSP pages is harder to debug.
 It is generally accepted practice not to mix complex business logic with presentation logic. JSP pages
are primarily intended for presentation logic.
 Code containing Java code, HTML and other scripting instructions can be hard to read.

2.4 General JS Coding Standards

Indentation
Use an indent of 2 spaces, with no tabs. No trailing whitespace.

String Concatenation
Always use a space between the + and the concatenated parts to improve readability.
var string = 'Foo' + bar;
string = bar + 'foo';
string = bar() + 'foo';
string = 'foo' + 'bar';
When using the concatenating assignment operator ('+='), use a space on each side as with the assignment
operator:
var string += 'Foo';
string += bar;

CamelCasing
Variables and functions in JavaScript should be lowerCamelCased. The first letter of each variable or function
should be lowercase, while the first letter of subsequent words should be capitalized. There should be no
underscores between the words.

10
Semi-colons
JavaScript allows any expression to be used as a statement and uses semi-colons to mark the end of a statement.
However, it attempts to make this optional with "semi-colon insertion", which can mask some errors and will
also cause JS aggregation to fail. All statements should be followed by ; except for the following:
for, function, if, switch, try, while
The exceptions to this are functions declared like:
do {
// Statements...
} while (condition);
These should all be followed by a semi-colon.
In addition, the return value expression must start on the same line as the return keyword in order to avoid semi-
colon insertion.

Control Structures
These include if, for, while, switch, etc.
if
if (condition1 || condition2) {
action1();
}
else if (condition3 && condition4) {
action2();
}
else {
defaultAction();
}
Control statements should have one space between the control keyword and opening parenthesis, to distinguish
them from function calls.
It is strongly encouraged to always use curly braces even in situations where they are technically optional.
Having them increases readability and decreases the likelihood of logic errors being introduced when new lines
are added.
switch
For switch statements:
switch (condition) {
case 1:
action1();
break;
case 2:
action2();
break;
default:
defaultAction();
}

11
Instead of complex if else structure, switch statement must be used.
try
The try class of statements should have the following form:
try {
// Statements...
}
catch (error) {
// Error handling...
}
finally {
// Statements...
}

Functions
Function and method names
 Functions and methods should be named in lowerCamelCase.
 Function names should begin with the name of the module or theme declaring the function to avoid
collisions.
Function Declarations
 There should be no space between the function name and the following left parenthesis.
 Exception: If a function literal is anonymous, there should be a single space between the word
"function" and the left parenthesis "(". Otherwise, it can appear that the function's name is actually
"function".
 Define optional arguments (using default values) at the end of the function signature.
 Always attempt to return a meaningful value from a function if one is appropriate.
Function Calls
Functions should be called with no spaces between the function name, the opening parenthesis, and the first
parameter; spaces between commas and each parameter, and no space between the last parameter, the closing
parenthesis, and the semicolon. Here's an example:
foobar = foo(bar, baz, quux);
As displayed above, there should be one space on either side of an equals sign used to assign the return value of
a function to a variable. In the case of a block of related assignments, more space may be inserted to promote
readability:
short = foo(bar);
longVariable = foo(baz);

Variables and Arrays


All variables should be declared with var before they are used and should only be declared once. Doing this
makes the program easier to read and makes it easier to detect undeclared variables that may become implied
globals.

12

Vous aimerez peut-être aussi