0% found this document useful (0 votes)
12 views

Java_Programming_Guidelines_v2.0

Uploaded by

rupal.patoliya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Java_Programming_Guidelines_v2.0

Uploaded by

rupal.patoliya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Standards – Coding in JAVA

Java

Programming

Guidelines for

PF Projects

Datamatics Company Page 1 of 31


Standards – Coding in JAVA

1 Introduction 3
1.1 Goals of these standards ..............................................................................................3
1.2 Scope and application of these standards ................................................................3
1.3 What is expected of everyone... .................................................................................4
1.4 References .......................................................................................................................4
2 General Coding Guidelines 5
2.1 Java Grammer.................................................................................................................5
2.2 Parentheses .....................................................................................................................5
2.3 Constants .........................................................................................................................5
2.4 Magic Numbers ...............................................................................................................5
2.5 Debugging........................................................................................................................5
2.6 Asserts ..............................................................................................................................5
2.7 Minimize * Forms Of Import ........................................................................................6
2.8 Compose Your Methods ................................................................................................6
2.9 Make Execution Structure Obvious ............................................................................6
2.10 Declare a Local Variable Where You Know Its Initial Value ..................................6
2.11 Avoid Assignments (``='') Inside If And While Conditions ..................................6
2.12 Embed Casts In Conditionals .......................................................................................7
2.13 Inner Classes...................................................................................................................7
2.14 Threads.............................................................................................................................8
3 Naming conventions 9
3.1 General Naming Conventions ......................................................................................9
3.2 Naming Conventions for Various Constructs.................................................................. 11
4 Formal and stylistic Fundamentals 14
4.1 Parenthesis ................................................................................................................... 14
4.2 Spacing .......................................................................................................................... 14
4.3 Braces ............................................................................................................................ 15
4.4 If / Else .......................................................................................................................... 15
4.5 While .............................................................................................................................. 16
4.6 Try/Catch/Finally ......................................................................................................... 16
4.7 Declarations.................................................................................................................. 16
4.8 Statements ................................................................................................................... 18
5 File Organisation 21
6 Comments 23
6.1 Implementation Comment (IC)................................................................................ 23
6.2 Documentation Comment (DC)................................................................................ 23
7 Specific Coding Guidelines for APZV Services 25
7.1 SQL Maps Naming Conventions for APZV Services.............................................. 25
7.2 EZF to IBatis migration .............................................................................................. 26
7.3 DAO Naming conventions.......................................................................................... 26
7.4 Business objects to be kept intact........................................................................... 26
7.5 Use of MidWay/QueryHelper classes....................................................................... 26
7.6 Exception Handling ..................................................................................................... 27
7.7 Miscellenous ................................................................................................................. 27
8 Eclipse Plug-In Naming Conventions 28
9 Tool Based Code Review 29
10 Code Review Checklist 30

Datamatics Company Page 2 of 31


Standards – Coding in JAVA

1 Introduction

This document is intended for all team members working on Java projects for PostFinance. The
listed rules and recommendations are obliging but can be adapted to changing customer needs if
necessary.
The document starts with general guidelines, naming conventions and stylistic fundamentals fol-
lowed by the tool based code review and code review guidelines.
This document also covers the Eclipse Plug-ins naming conventions as well as some project specific
coding guidelines.
These standards will be used in code reviews and should be referred to when creating code.

1.1 Goals of these standards


First of all there is the need to recognize the purpose of these guidelines and set some goals.
Following are three basic, but very important goals:

• The use of these guidelines should result in readable code and should encourage adher-
ence.

• The resulting documentation should be easy to maintain.

• This document should be a living document in that as we discover better ways to do things,
it gets reflected here.
In order to write great software, you have to write software greatly. Well, the point is that before
you can produce great code, you have to have developed a process for writing great code. And that
is what these standards are intended to help with.
Some amount of standardization is especially important in a large development organization writing
component software. Everybody will be in everybody else's code, and that code must be clear. It
must be clear what the code does, how it should be used, how it can be extended, etc. The stan-
dards within this document have been written to balance the group need for standardization with
the individual's desires to code in the ways they feel most efficient.

1.2 Scope and application of these standards


It is very important to note that this document is divided into two distinct areas – Guidelines and
review checklist. It is very important to recognize the following.

• Guidelines are "suggested" coding practices that have been written to recognize the need
for individuality AND for common coding practices. The purpose of the guidelines is to pro-
vide a framework upon which we can all create better code. However, the guidelines are
not meant to impede engineering efforts when these guidelines are found to be in direct
conflict with an individual's preference, so long as that preference is implemented consis-
tently and is well documented. Finally, because we recognize that this opens the code upon
to individual stylist coding habits, it is important that these habits are well documented and
will then become the basis for all other updates within the affected files, i.e. when in some-
one else's code do as they do.

• Review checklist describes the checklist developer should follow while doing the self review.
The same checklist should be used while doing the peer review as well. Review checklist is
very small and concise keeping it as a small handbook; that does not mean that one should
look at only the checklist not at the guidelines. Good reviews are possible only if these
guidelines and checklist are religiously followed.

Datamatics Company Page 3 of 31


Standards – Coding in JAVA

1.3 What is expected of everyone...

• Everyone should read these guidelines.

• Everyone should understand them.

• Everyone should use them.

• Then and only then should anyone begin to challenge them*.


*Ultimately, everyone is expected to help refine the rules embodied in this document.

1.4 References
[Sun97] Sun Microsystems: Java Code Conventions.
http://java.sun.com/docs/codeconv/index.html

Datamatics Company Page 4 of 31


Standards – Coding in JAVA

2 General Coding Guidelines

2.1 Java Grammer


Wherever appropriate, avoid code that embeds many operations in a single line. For ex-
ample, avoid:
someObject.doThis(i++, otherObject.someField.doThat(), x?y:z).
This kind of code is error prone, difficult to decipher, and hard to maintain.

2.2 Parentheses
Parentheses are recommended for Boolean expressions to ensure proper evaluation.
Example:
if (((someValue<foo(theParm)) && anotherValue) || todayIsMyBirthday)

TIP: Place constants on the left side of your expressions; assignment, boolean and other-
wise. This technique can catch assignment (versus equality) errors, as well as promote
constant factoring for poor quality compilers.

2.3 Constants
Constants will use upper case.
Example
static final float PI_VALUE = 3.14159;
static final int DAYS_IN_WEEK = 7;

2.4 Magic Numbers


Literal ordinal constants embedded within source should be avoided. Whenever possible,
use constants instead of literal ordinal constants:
Example
int totalDays = 10 * DAYSINWEEK;
static final int kDaysInWeek = 7;

2.5 Debugging
Whenever a new Method or function is defined, all possible test cases should be identified
and tested against then and there. It will reduce bugs at the preliminary stage.

1. Make sure every path of execution through your code has been thoroughly tested. You can
never do enough coverage testing. Here's a neat idea: try actually stepping through each
line! While you're hard at work testing your code, be sure to throw invalid inputs at every
public interface you provide. The last thing we want to do is crash because your routine
didn't handle invalid inputs from ours. Never ever check in code that doesn't compile.

2. Want to know the secret to fast code? Calculate those comparison values once: reuse them
often. Avoid global variables too, since they can wreak havoc with the pre-fetch instruction
queue.

3. It is our policy to produce code that can test itself to the greatest extent possible. To that
end, we encourage the use of three debugging techniques: asserts, pre/post conditions and
self testing methods.

2.6 Asserts
It is highly recommended that assert methods (warnings/errors) be used wherever highly
required to aid in debugging, especially to verify assumptions made in code. This will be
the technique used for reporting run-time errors and warnings.

Datamatics Company Page 5 of 31


Standards – Coding in JAVA

2.6.1 Pre and Post Conditions


In order to bulletproof your code, you should use asserts to test all boundary conditions.
You're not doing any favors for anyone by "defensive" programming practices that allow
clients of your code to make improper calls. In other words, it is better to blow up in de-
bug builds if you are given bad data rather than trying to "fix" the data and hide bugs.
Example
String copyString(String aOtherString)
{
Assert.PreCondition(NULL != aOtherStr, "Null string given");
...
Assert.PostCondition(fSelfString.length() >=aOtherString.length(),
"lengths don't match after copy.");
}

We do not want debug code to be included into release builds. Therefore, all assertions are
removed by the compiler (the java equivalent of #defines) by flipping the debug flag in the
Assert class.

2.7 Minimize * Forms Of Import


Minimize * forms of import. Be precise about what you are importing. Check that all de-
clared imports are actually used.

Rationale

Otherwise readers of your code will have a hard time understanding its context and de-
pendencies. Some people even prefer not using import at all (thus requiring that every
class reference be fully dot-qualified), which avoids all possible ambiguity at the expense of
requiring more source code changes if package names change.

2.8 Compose Your Methods


After you have defined the public operations that a class has to perform, you will need to
implement those operations with methods. Focus on communication and maintainability
when implementing methods. "Divide your program into methods that perform one identifi-
able task. Keep all of the operations in a method at the same level of abstraction. This will
naturally result in programs with many small methods, each a few lines long."

2.9 Make Execution Structure Obvious


Try to make the execution structure of your method visible when looked at quickly. Stan-
dardize on a few good structures so a reader will quickly be able to survey the functionality
and identify where to look for interesting features.

2.10 Declare a Local Variable Where You Know Its Initial Value
Declare a local variable only at that point in the code where you know what its initial value
should be.

Rationale

Minimizes bad assumptions about values of variables.

2.11 Avoid Assignments (``='') Inside If And While Conditions


Avoid assignments (``='') inside if and while conditions.

Rationale

They are almost always typos. The java compiler catches cases where ``='' should have
been ``=='' except when the variable is a boolean.

Datamatics Company Page 6 of 31


Standards – Coding in JAVA

2.12 Embed Casts In Conditionals


For example:
C cx = null;
if (x instanceof C)
{
cx = (C) x;
} else
{
evasiveAction();
}
Rationale

This forces you to consider what to do if the object is not an instance of the intended class
rather than just generating a ClassCastException.

2.13 Inner Classes


This form of classes is mainly used in GUI-programming.
⌦ Because they can lead to special and undesirable situations and are not always really
readable, they should be used only when helpful and well considered. The table below
shows their correct usage.

Type Usage
Nested top-level • Must be declared static.
classes and inter- • Only the access to static variables and methods of the outer
faces class is possible.
Therefore the usage of this type is forbidden!
Member classes • Must not be declared static.
• Not so restricted access to the outer class as top-level
classes and interfaces.
Typical helper classes.
Local classes • Can’t contain fields, methods or classes which are declared
static.
• Their scope can’t be changed.
• The inner class has access to all attributes of the outer class.
Adapter class, especially used for the implementation of a
listener.
Anonymous classes • A variant of local classes without a class name.
• Are declared and instantiated in one single statement.
Same usage as local classes, but anonymous classes should
be preferred over local classes in the following cases:
- When the class has a very short body;
- if only one instance is needed;
- the class will be used directly after their definition;
- if its not at the expense of readability, what means that
the name of the class is irrelevant.

Datamatics Company Page 7 of 31


Standards – Coding in JAVA

2.14 Threads

In Java, threads are an integral part of the language and are built-in seamlessly into the
object-oriented concepts. They form the basis for the parallel code execution in one single
process. The disadvantage of threads is the increased potential of possible inconsistencies
and deadlocks.
⌦ If there has been an extra effort to synchronize the class, method, or a certain code
block you must document it in the comment accordingly. Furthermore you should only ex-
ert influence on the priority scheduling if really necessary. You may not take some assump-
tions about the scheduling because this depends on the operating system and the JVM
used.
The second problem that has mentioned previously is the occurrence of deadlocks. This
happens when each process in a set wait for an event of another process from this set.

⌦ Think twice and use in an accurately manner the synchronized keyword1. Last but not
least you loose potential concurrency when synchronizing sections.

Datamatics Company Page 8 of 31


Standards – Coding in JAVA

3 Naming conventions
3.1 General Naming Conventions

3.1.1 Name Types Well


Spend the time to name a Type correctly and concisely. The name should match the range
of usage for the Type: if it is very general, choose a very simple name; and if it is only ap-
plicable in a specific context, qualify it to describe that limitation. Sometimes naming a
Type can be very easy because it exists as part of the business concepts (an Employee) or
part of the solution (a Window). But always make sure the name really matches the con-
cept. And really care about the name: "Be a poet for a moment."

Rationale

Type names provide the main glossary and conceptual skeleton for any OO system.

3.1.2 Only Expose Responsibilities


Only expose the features that you want to be responsible for. A Type provides a contract to
all its customers that it will need to maintain "for life", so never publicly expose something
you do not want to be responsible for maintaining. Make sure all instance variables and im-
plementation specific methods are hidden from clients and do not become part of your re-
sponsibilities.

Rationale

This is one of the foundations of OO and software engineering.

3.1.3 Operations
Operations formally define the exterior of an Object: what messages it can understand and
the contract it agrees to if you send it that message. Operations must be understandable in
the context of the current Type (Interface or Class) and should be consistent across multi-
ple Types. This requires continuous OO thinking, strong efforts toward standardization, and
vigilant semantic verification. There are many more operations than types, so it is a much
more difficult task to name and organize them well.

3.1.4 Choose Intention Revealing Operation Names


Choose "intention revealing operation names" is the primary rule for naming operations.
Always create a name that suggests what the operation "provides for the caller", not how a
method could accomplish this service.

Rationale

The clearer you describe the behavior of the operation within its name, the easier it is for
the clients (who repeatedly use those operations) to understand your class or interface.
This is one of the many incarnations of thinking from the client’s perspective.

3.1.5 Have Uniquely Named Signatures


Ideally, make each operation have a unique name if it has different behavior or a different
number or parameters. This will allow a client to know what this particular operation does
and how many parameters it requires simply from the operation name. Especially avoid
creating operations with the same name and the same number of arguments but different
argument types.

Rationale

Otherwise, the human reader has to act like a compiler and figure out which operation (of
several identically named ones) is the proper one to call given all the variable types in-
Datamatics Company Page 9 of 31
Standards – Coding in JAVA

volved. Because this is all done at compile-time, usually the result is not what anyone
would want. See "Avoid overloading methods on argument type" for a good example in
Java.

3.1.6 Standardize Naming Patterns


Standardize the vocabulary used in operation names. As much as possible, words should be
used consistently and uniquely when part of an operation.

Rationale

This makes understanding operations easier and supports precisely describing new func-
tionality. These benefits become especially important as a system grows.

Details and Examples

The following is an example subset of the standard meanings for operation name parts and
operation categories (see the Source code format section below).

Common operation prefixes

Prefixes Category Description

find Searching Retrieve a single object or null if unsuccessful

select Searching Retrieve multiple objects or an empty collection

add Add an object to a collection

Type specific prefixes

Prefixes Category Description

is, can, Testing Return a Boolean and test the state of the object
has, will

new Creating Create and return a new object from a factory that creates
only a single type of object

init, setup Initializing These methods are called before you can use an object.
Only a single init function should be called which can then
be followed by whatever setup methods you need to change
the default configuration of the object.

Non-prefix operation name patterns

Prefixes Description

any Return any object that satisfies the request (findAny)

all Return all objects that satisfy the request (selectAll)

Within each Type or domain area (Collections, Functors, SQL, Mapping, Domain models)
there will be both reused vocabulary and new vocabulary. Try to manage these forces well.

3.1.7 Categorize Your Operations


Group operations into Categories and reflect those categories in your Interfaces. If a lan-
guage or tool does not support operation categories, use whatever documentation is avail-
able (comment dividers, notes, etc.).

Rationale

Datamatics Company Page 10 of 31


Standards – Coding in JAVA

By grouping operations into meaningful categories it will be easier to understand the opera-
tions and to read the implementations. This organizational assistance is something akin to
"subtyping" of operations. Some example categories are:

Constructing A section and category. The constructors for the class.

Initializing An additional method that should be applied directly after constructing the
object.

Setup Methods that can optionally be applied to an object but must be done im-
mediately after construction and initialization and before using the object
normally.

Validating Check whether the current object is in an acceptable state (could also be
under asking if this is possible after construction is finishing).

Asking Asking the state of the current object without causing any (visible) side
effects. A pure function. ISE Eiffel ‘Query’.

Testing An asking method that returns a Boolean value

These categories should align with and reinforce operation naming patterns.

3.2 Naming Conventions for Various Constructs


For better comprehensibility the following naming conventions have to be respected:

Type Naming rules Examples


Package Own packages are composed of the Post package ch.post.pf.nf;
domain, the business unit and the pro-
ject name (everything in lower case
letters).

Classes Class names are substantives and the public class Batch;
first letter of each partial word is always public class JournalHome;
in upper case. In addition the names
public class URLLoader;
should be simple, descriptive, and not
contain any abbreviations (except if they
are widely known and accepted).

Interfaces The same guidelines as for class names. Interface Storeable;


But interface names are often verbs and Interface Moveable;
end with able.
Methods run();
o Method names should be chosen as
verbs, whereas the first letter is in runFast();
lower case and the first letter of getBackground();
each subsequent partial word is in
upper case.

o Getters and setters should begin


with "get" / "set" and return the
appropriate object type.

o Boolean getters should use "is" or


"can" as a prefix, such as "isUndo-
able()" rather than "getUndoable()"
Variables Variable names begin with a lower case int arrayLength;
letter, whereas the first letter of each static int s_count;
subsequent partial word is in upper case.
Datamatics Company Page 11 of 31
Standards – Coding in JAVA

Abbreviated names are only allowed for float m_shapeWidth;


temporary variables.

Constants All letters in the name of a constant are static final int MIN_WIDTH = 4;
written in upper case and each partial static final int MAX_WIDTH =
word is separated by an underline char- 999;
acter.
Parameter Parameter names should be constructed public boolean numberIs-
Names like identifiers, and include the type in Even(int aValue, Object anOb-
the name if the type is not explicit. They ject) {
begin with lowercase letters, and they ...
typically start with the letter "a". Some
}
may feel "an" is more readable for pa-
rameters that start with a vowel, such as
"anObject."
Component public class WidgetFactory
A component factory is a public class
Factory that implements only static methods. {
Names These static methods are "Factory func- static Button MakeButton(int
tions" or "component constructors". aButtonType);
Factory class names should include the
word "Factory". Factory method names static ListBox MakeListBox();
should start with the word "Make." For };
example,

⌦ In addition the following naming conventions have to be respected:


• Methods that read or set the value of attributed (also known as getter and setter methods),
must use the name getX() and setX()(with X as attribute name).
Example: getFont() and setFont() from java.awt.Component.
• A method that performs a boolean test, should be names in the form of isX() or hasX()
(with X for the boolean condition).
Example: isEnabled() from java.awt.Component or hasMoreElements() from
java.util.Enumeration.
• Subclasses of java.util.EventObject should to be denoted with XEvent (whereas X stays for
the name of the event).
Example: ButtonPressedEvent
• Sub classes of java.util.EventListener should be denoted with XListener (whereas X stays
for the name of the event, on which the listener is registered).
Example: ButtonPressedListener, if the event is of type ButtonPressedEvent.
• The registration of an EventListener is done with addX() and removeX() (whereas X is the
EventListener type).
Example: addKeyListener(), removeKeyListener() from java.awt.Component.
The name should not be composed of more than three partial words. In addition the name
should be chosen in a manner that is similar to the functionality it performs. For variables
special guidelines exist:
• Instance variables (dynamic, also denoted as attributes) start with m_ (this is not count as
a partial word).
• Class variables (static) start with s_ (this is not count as partial word).
• Constants have no special qualifier; they follow the format as shown in.

Datamatics Company Page 12 of 31


Standards – Coding in JAVA

Often it makes sense to use short names for variables. On the one hand because this is a
common practice; on the other hand because there exist variables which are not so impor-
tant and are used rather temporary.

⌦ Under these circumstances the following mnemonics are allowed:

Type Identifier
Character c
Index i, j, k
Counter m, n
Object o, obj
Exception e, ex
String s, str

Datamatics Company Page 13 of 31


Standards – Coding in JAVA

4 Formal and stylistic Fundamentals


This chapter contains guidelines related to the correct usage of parenthesis, as well as the
right spacing and line breaks.

4.1 Parenthesis
In statements where the precedence is not clearly visible, use parenthesis – even if would be
logically not really necessary.

if (a == b && c == d) // AVOID
if ((a == b) && (c == d)) // RIGHT

For a class, interface, method, and block declarations the open curly brace is placed on a
single line directly below the start of the declaration. Similarly, the closed curly brace must
be placed on a single line in the same column as the corresponding open brace.

public class MyClass


{
public void myMethod()
{
while (condition1)
{
if (condition2)
{
...
}
}
}
}
Exceptions:
• Initialisation of arrays.

4.2 Spacing
Blank lines improve the readability by grouping coherent sections or separating them from
disparate sections. So place a blank line;
• between package and import declarations;
• between methods;
• between the local variables and the first statement of a method;
• between logical sections of a method;
• In front of comment etc.

The following guidelines are related to spaces:


1. The normal indention is four spaces (Note: Tabs are not be used.)
2. between a keyword and a parenthesis (Exception: between method names and paren-
thesis)
3. after each comma and semicolon (Exception: not necessary at the end of the line)
4. between binary operations and their operands (Exceptions: between unary operations
and the operand and between the dot and the operand)
5. after the type cast
Datamatics Company Page 14 of 31
Standards – Coding in JAVA

Example Rule
myMethod(String str, int count) Exception 2, rule 3
{
for (int i = 0; i < count; i++) Rules 1, 2, 3, 4, exception 4
{
a = (a + c) / (c * d); Rules 1, 4, exception 3
this.m_str = str; Exception 4
}
myMethod2((byte) b, (Object) obj);
} Rule 5

In addition, lines may not exceed the 100 character limit, because not all terminals, devices,
and tools handle them correctly. So for the line break, following rules have to be respected
(in descending priority):

1) Line break after comma


2) line break before arithmetic operators
3) line break after logical operators
4) the new line has to start at the same position as the corresponding expression of the
previous line
5) If the rules above are not applicable, so the indention of the new line is 8 spaces more
than the one of the previous line

var = function1(longExpression1, // rule 1


function2(longExpression2, // rule 1, 4
longExpression3)); // rule 4

longName1 = longName2 * (longName3 + longName4 – longName5)


+ 4 * longName6; // rule 2, 4

result = (condition1 && condition2) || (condition3 && condition4) ||


(condition5 && condition6); // rule 3, 4

protected static synchronized workingLongMethodName(int anArgName,


Object anotherArgName); // rule 4, 5

4.3 Braces

• The starting brace can be optionally at the end of the conditional or on the next line
aligned with the conditional. The ending brace must be on a separate line and aligned
with the conditional. It is strongly recommended that all conditional constructs define a
block of code for single lines of code.

• We give some options below to accommodate the vast majority of programmer's styles.
HOWEVER, be consistent! When you pick a style, stick to it. When editing another per-
son's code, respect the code, copy the style. (When in Rome, do as the Romans do).

4.4 If / Else
Place the IF keyword and conditional expression on the same line.
Examples:

Datamatics Company Page 15 of 31


Standards – Coding in JAVA

if (expression)
{
statement;
}
else
{
statement;
}

4.5 While
The WHILE construct uses the same layout format as the IF construct. The WHILE keyword
should appear on its own line, immediately followed by the conditional expression. The
statement block is placed on the next line. The curly braces may optionally be indented by up
to 1 tab character. (1 TAB=2 spaces).
examples:
while (expression)
{
statement;
}

4.6 Try/Catch/Finally
The try/catch construct is similar to the others. TRY keyword should appear on its own line;
followed by the open brace (optionally on the same line); followed by the statement body;
followed by the close brace on its own line. Any numbers of CATCH phrases are next consist-
ing of the CATCH keyword and the exception expression on its own line; followed by the
CATCH body; followed by the close brace on its own line. The FINALLY clause is the same as
a CATCH.

Examples:
try
{
statement;
}
catch (ExceptionClass e)
{
statement;
}
finally
{
statement;
}

4.7 Declarations
• For the purpose of adding comments, one line for each variable should be used.
int level; // indention level
int size; // size of the table

• The declaration of different data types on the same line is forbidden.


Datamatics Company Page 16 of 31
Standards – Coding in JAVA

int foo, fooArray[]; // WRONG

• In principle, variables should be declared at the beginning of a block that is surrounded by


curly braces. If possible the variables should be initialised at the time of their declaration.
One possible exception is, if the initial value of the variable depends on subsequent calcula-
tions.

public void myMethod()


{
int count = 1; // beginning of method block

if (condition)
{
int value = 0; // beginning of the if-block
...
}
}

Exception:
• Situations can come up, where it may be useful to declare the variable not until its first us-
age (mainly if it is a temporary variable and only valid for a certain scope, typically in a for
loop).

for (int i = 0; i < MAX_LOOPS; i++)

• Due to undesirable side effects and hardly comprehensible control flows the overwriting of
variables by using the same name is forbidden. That means you may not use the same vari-
able in an inner block, when there is already a declaration in the outside block.

public void myMethod()


{
int count;

if (condition)
{
int count; // AVOID
...
}
}

Datamatics Company Page 17 of 31


Standards – Coding in JAVA

4.8 Statements
• Each line may contain at most one statement, consequently the usage of the comma op-
erator for the purpose of grouping is forbidden.
if (err)
{
argv++; argc++; // AVOID
format.print(System.out, “error”), exit(1); // AVOID
}

• That implies for each line at most one variable may be changed (updated).

a += b++ + c; // AVOID
a = a + b + c;
b++; // RIGHT

• Additionally the assignment of several variables to the same value in a single statement is
forbidden. The same is true for nested assignments, even if they were used for runtime
improvements. That is left to the compiler.

fooBar.fChar = barFoo.lChar = 'c'; // AVOID


barFoo.lChar = 'c';
fooBar.fChar = barFoo.lChar;

d = (a = b + c) + r // AVOID
a = b + c;
d = a + r; // RIGHT

• A method returning a value (also known as function) should do this only at one place,
which means this method has only one return statement.

if (condition) if (condition)
{ {
return true; return x;
} }
else else
{ {
return false; // AVOID return y; // AVOID
} }

return condition; // return (condition ? x : y); // RIGHT


RIGHT

Conditional statements may occur in the form of if then else or as a switch statement.
• The last case statement of the switch form is always a default clause. In addition all the
case statements must be finished with a break clause otherwise it should be marked with a
// fall-through comment. This leads to the following form:

switch (condition)
Datamatics Company Page 18 of 31
Standards – Coding in JAVA

{
case ABC:
statements;
// fall-through
case XYZ:
statements;
break;
default:
statements;
break;
} // end switch

Note:
At the end of each conditional construct we suggest to put a comment of the form
// end if and // end switch respectively to improve the visualisation.

• The usage of break and continue in loop constructs should be avoided. It would be better to
use boolean variables.
For loop constructs the following statements exist:

for (init; condition; update) while (condition) do


{ { {
statements; statements; statements;
} // end for } // end while } while (condition);

Note:
At the end of for and while loops comment should placed in the form // end for and // end
while respectively.
Except for the do while loop, because after the closing curly brace the keyword while is
placed, so no additional comment in the form of // end while is necessary.

• The exception handling in Java is a mechanism that manages the different failures like se-
mantic violations and application specific exceptions in a robust manner.
try
{
statements;
}
catch (ExceptionClass e)
{
statements;
}
finally
{
statements;
}

If inside the try block an exception is raised, it is checked if a corresponding catch block is
available. If yes, it will be executed; otherwise the exception is propagated to the caller.

Datamatics Company Page 19 of 31


Standards – Coding in JAVA

This is repeated until the exception is handled or the main method is reached. The finally
block will always be executed, both in the normal case, as well as in the exceptional case2.
In the context of exception handling the following points should be noted:
• Programming errors and java.lang.RuntimeException generally won’t be raised, but
sent up the code hierarchy and the entire exception stack will be dumped.
• If an error in a method occurs that it can’t handle itself, then an exception is thrown. If
it is an exception that should be handled by the caller, then throw a checked3 excep-
tion.

2 Typically here you close open file handles, database connections and similar things.
3 These are objects of the type java.lang.Exception and its subclasses, except for java.lang.RuntimeException.
Datamatics Company Page 20 of 31
Standards – Coding in JAVA

5 File Organisation
• A class should not exceed the size of five pages (circa 1000 lines). Methods should not be
larger than one page (circa 200 lines). Basically a file contains exactly one class or inter-
face. The only exception is the usage of local or anonymous classes (see chapter 0), espe-
cially helpful in the GUI-programming for the event handling.
• In addition the source code is written in English for internationalisation purposes.
• Each Java source code file must begin with a file header, followed by the package and im-
port statement and a class or interface implementation/declaration. A typical file header
looks like:

/*
* ----------------------------------------------------
* © <YEAR> by PostFinance
* ----------------------------------------------------
* Project:
* Layer:
* File:
* ----------------------------------------------------
* When Who Description
* ... ... ...
* ----------------------------------------------------
*/

Note:
o When: Format dd-mmm-yyyy with mmm being in Jan, Feb, Mar, Apr, May, Jun, Jul,
Aug, Sep, Oct, Nov, Dec.
o Who: Format V Jain,
o Description: Explanations of the changes that have been done.
o Layer: Indication of the affected layer, as for example database, business logic, presen-
tation, technical component etc.

• A typical Java source code file shows the following structure:

Parts of the- Notes


class/interface decla-
rations
1 File header The format is explained above.
2 Package/import state- –
ment
3 Class/interface documen- See chapter 6.2.
tation (/** ... */)
4 Class/interface statement –
5 Documentation of the Should contain class and interface wide information that
class/interface implemen- is not covered in point 3 and therefore not extractable by
tation (/* ... */) javadoc.

6 Constants Are defined with static final, see

Datamatics Company Page 21 of 31


Standards – Coding in JAVA

7 Class variables (marked They are grouped based on their scope (from the most
as static) general to the most restrictive).
8 Instance variables They are grouped based on their scope (from the most
general to the most restrictive).

9 Initializer An initializer is used for complex initialisations of vari-


ables, fields objects etc. Each class may only declare one
static and one instance initializer.

10 Constructor They are grouped based on their scope (from the most
general to the most restrictive).

11 Methods The methods should be grouped based on their function-


ality and not due to their scope or accessibility (public,
private, etc.).

12 Member classes See chapter 0.

⌦ Related to the scope (visibility) of classes, methods, and variables the following points
should be noted:
• The scope of a class, interface, method and variable should always be as restrictive as pos-
sible and reasonable.
• Instance and class variables may not be declared public, they should always by accessed
from outside via corresponding methods.
• The usage of class variables and class methods via an instance is best avoided. A class
should be used instead of that.

anObject.classMethod(); // AVOID
AClass.classMethod(); // RIGHT

Datamatics Company Page 22 of 31


Standards – Coding in JAVA

6 Comments
Comments form an important part of the source-code. They are indispensable for the compre-
hension and simplify the tasks of maintenance and extension.
Due to the internationalisation the comment is written in English.
We differentiate two types; the implementation comment and the documentation comment.
The former serves for the explanation of important or non-trivial code sections. The latter de-
scribes the specification of the code and can be automatically extracted by javadoc.

6.1 Implementation Comment (IC)


The IC in the source code consists either of an End-of-Line or a block comment. Both are ig-
nored by javadoc.
• The End-of-Line comment (Format: // ...) holds from its declaration until the end of the
line. Accordingly you can use an IC to comment out the entire line or use it as a trailing
comment behind the statement.
• The block comment (Format: /* ... */) is mainly used to comment out entire code sec-
tions.

6.2 Documentation Comment (DC)


With the use of javadoc the DC (Format: /** ... */) is automatically extracted of the source
code and generates a complete documentation in HTML style. To effectively use this function-
ality, some guidelines have to be respected.

/**
* <dl>
* <dt><b>Purpose:</b>
* <dd>The <code>Example</code> class provides...</dd>
*
* <dt><b>Note:</b>
* <dd>This class is thread-safe, so their members
* can be accessed concurrently by multiple
* threads without danger of inconsistencies.</dd>
* </dl>
*
* @version 1.01, 07-Jun-1975
* @author V. Jain, DL
*/
public class Example
Note:
o <code>...</code> is used to highlight names or parameters.
o HTML tags are only necessary, if there are no corresponding Java tags existing.
o Version, Author and Note (usage, bugs, known problems, open or important points
etc.,) are optional.

o Each method – except main(String[] args) – should have a DC with the following format:

/**
* <code>myMethod</code> performs count times an arithmetic
Datamatics Company Page 23 of 31
Standards – Coding in JAVA

* operation with <code>op1</code> and <code>op2</code>.


*
* <dl>
* <dt><b>Requires:</b><dd>count > 0</dd>
* </dl>
*
* @param count The number of loops.
* @param op1 First operand.
* @param op2 Second operand.
* @return Result of the arithmetic operation.
*/
public float myMethod(int count, float op1, float op2)

Note:
• Each parameter (@param), each return value (@return) and each exception
(@exception/@throws) has to be declared in the DC according to the template above.
• The documentation of the assertions (require and ensure) is optional.

Tags Function Usage


@author If there are more authors, they @author <name>, <company>
are mentioned in chronological
order (write them below each
other).

@deprecated Indicates the user of this method Often it is used in combination with
that this method should no longer @see or {@link}, which indicates the
be used. new method that should be used
instead.
@deprecated <deprecated-text>

@exception Each exceptional case that is de- The tags are listed in alphabetical
or clared in the throws clause must order.
be commented. @exception <description>
@throws

{@link} Creates an in-line link to another Format:


position in a file or to an URL {@link <name> <label>}
without the heading of @see.

@param Each parameter is declared in the In methods and constructors:


same order as the declaration @param <name> <description>
found in the method signature.

@return Each method that returns a value In methods und constructors:


(inout, out) and therefore have @return < description >
not been declared with void.
@see Creates a reference named "See Format:
Also" to another position in a file @see <reference>
or to an URL.
@since Can be used for the description of Format:
changes that are done since a @since <since-text>
certain version or time.
@version Contains the version (ma- In classes and interfaces:
jor.minor) and the date. @version <x.xx> <dd-mmm-yyyy>

Datamatics Company Page 24 of 31


Standards – Coding in JAVA

7 Specific Coding Guidelines for APZV Services


7.1 SQL Maps Naming Conventions for APZV Services

a) There would be one SQL Map for each provider method.


An exception to this rule would be the method-specific-keyword or category mapping
out to more than one provider method.
The namespace of the SQL Map would be named as
1. <service-name>.<category> or
2. <service-name>.<method-specific-keyword>.

An exception is logic-buchung, which for sake of traceability and reusability, has used
the original method names as the sql maps id. Some more exceptions can be found in
services from earlier iterations.

Example for 1: partner.izvPartner (where IzvPartner is a category of Partner).

Example for 2: findCmsCode (in Journal service) would have the following namespace:
journal.cmsCode

findCmsJournalById (in Journal service) would have the following namespace: jour-
nal.cmsJournal

Note: The keyword should follow the java naming convention.

The name of the SQL Map xml file would be the <category/method-specific-
keyword>_SqlMap.xml.

b) The DML xml fragments such as (select, update, delete, insert) would be named as:

<method-specific-keyword>.<provider-method-name> or

<category>.<provider-method-name>

However, if it’s a count query, then it could be denominated as:

<category/method-specific-keyword>.<provider-method-name>.countQuery

The name of the service would be prefixed to each of these DML xml fragments.

c) Further, the select (different from select query id) clause, from clause and where-
clause of the query would be termed as such:

<provider-method-name>.fullSelectClause

<provider-method-name>.fullWhereClause

<provider-method-name>.fullFromClause

Note: Each of these would be pre-fixed with <service-name>.<category/method-


specific-keyword>

d) The result map would be identified as follows:

<service-name>.<method-specific-keyword>.<provider-method-name>.fullResult.
Datamatics Company Page 25 of 31
Standards – Coding in JAVA

e) Naming convention for type handlers

Naming convention for type handlers would be

<TypeName>To<ObjectName>TypeHandlerCallback

e.g. BigDecimalToKontoNumber or StringToKontoNumber.

These type handlers would be used to convert the object to a particular type that the
database would understand and vis-à-vis database to the object type. This would be
done using the getter-setter methods.

7.2 EZF to IBatis migration


Original EZF code should be referred to, on line by line basis. All the QueryMapper and Re-
sultMapper should be scrutinized thoroughly for any missing implementation in iBatis sql
maps.

7.3 DAO Naming conventions


All the DAO classes should be named as <service-name>DAO and respective implementa-
tion should be <service-name>DAOImpl. Any discrepancy in the names should be re-
moved. Following names should not be allowed: <service-name>ProviderDAO etc.

There should be a single QueryHelper class for each service and should be named as <ser-
vice-name>QueryHelper. All the method required to process the search parameters in or-
der to make them compatible to iBatis sql maps should be named as preprocessQuery with
argument as the subclass of Query object or any other object containing search parame-
ters. The method should be overloaded for various different type of arguments.

7.4 Business objects to be kept intact


All the classes found under …business.object or object package of respective classes need
to be spared from any changes during the entire life cycle of project. In case some proper-
ties and/or getter methods are required, a separate MidWay object may be used, which can
extend the business object. This MidWay object should be placed under logic package of
respective service.

7.5 Use of MidWay/QueryHelper classes


A QueryHelper class is unique to each service and serves the following purpose:
o Provides methods for pre-processing of the Search Parameters before it send to iBatis
sql maps.
o Formulate specific MidWay objects and return them to the calling method.

MidWay classes are used for the following reasons:


o To bridge the compatibility gap between java data types and iBatis data types
o Some manipulation required on the data e.g. to apply indexOf or substring methods
o Different representation of same data in Java Classes and databases e.g. in database a
java date is stored as 8 or 14 digits value for date or timestamp respectively.
o Constants defined in java classes to be accessed in iBatis sql maps.
o Composite objects of parent class e.g. arrays were not accessible directly from iBatis
sql maps. To overcome this problem, a getter method is introduced in MidWay object
which in turn returns array of parent class.

Datamatics Company Page 26 of 31


Standards – Coding in JAVA

7.6 Exception Handling


No exception handling for DataAccessException is required at the DAOImpl or ProviderImpl
level. This has been handled in the framework classes.

7.7 Miscellenous
o Specific QueryHelper and ResultHelper objects in xxxProviderImpl classes should be
declared as member variables and not as local variables to each method.

o Remove multiple calls to query.validate() method. Assign result of query.validate()


method into a local variable and use that object for subsequent calls in xxxProviderImpl
methods.

Datamatics Company Page 27 of 31


Standards – Coding in JAVA

8 Eclipse Plug-In Naming Conventions

For Eclipse Plug-in naming conventions, refer to


Eclipse_Plugin_Naming_Conventions.doc provided by PF.

Eclipse_Plugin_Namin
g_Conventions.doc

Datamatics Company Page 28 of 31


Standards – Coding in JAVA

9 Tool Based Code Review

Most of the coding guidelines, style guide and naming conventions described above can be
configured in Eclipse IDE and Checkstyle.
Above setting are available in VSS along with the instructions for various projects.

Developer is expected to check & remove the checkstyle errors before doing check-in in the
repository.

The configuration file for NAPF is attached here.

NAPF_Checkstyle.xm
l

Datamatics Company Page 29 of 31


Standards – Coding in JAVA

10 Code Review Checklist

Sr. No. DO’s


File Header with project Name & layer (DAO, Service etc) should be present in all the classes.
1.
Dates in file header and class header should be the same.
2.

3. Class description with version should be present in all the java classes.

4. LOGGER statement should be provided wherever required.

5. Functional comments should be present wherever required.

TO-DOs must be added wherever code is temporarily added or code is incomplete. These TO-Dos
6. must be removed after code is complete.
Cyclomatic complexity should not be more than 10. Otherwise re-factor the method/class.
7. Exception to this is the xxxProviderImpl classes in APZV Services, whose methods originally coded
were not split to reduce Cyclomatic complexity.
Javadoc must be present for all the methods and classes. Checkstyle must not throw any error on
8. java doc. Exception to this rule: Only methods declared in interfaces bear the actual java-doc
comments. The implementation classes refer to those methods using non-javadoc.

9. Constant should be on the left hand side for equality check.


Use constants for String literals wherever possible. Exception to this rule is The Sql Map Ids are
10. still referred directly in xxxDAOImpl.

11. Use interface in declarations and method arguments (e.g. List myList and not ArrayList myList).

12. Use default class scope only when it is justified.


Utility classes should have a private default constructor with comment "// private constructor to
13. avoid instantiation".
DAO classes should be final and have a private default constructor with comment "// private
14. constructor to avoid instantiation".

15. Provide Comment for the COLUMN name in the SQL Query whenever column index is used.
Use Trace.trace(Theme.JDBC, " ## XXXDAO.methodName() Query ## :", query); for all the DAOs
16. using JDBC implementation.
See that Exception Handling is done as per the guidelines defined in the project. Ensure that there
17. is ultimately a catch for all unchecked exceptions.

18. See that Utility class name has Util as suffix. E.g. DateUtil

19. If you override equals(), also override hashCode()

20. Serial UID is a must in all the TOs

21. toString() is a must in all the TOs

22. Use constant instead of magic number


Most of the coding guidelines, style guide and naming conventions have been configured
23. in Eclipse IDE and checkstyle.Developer is expected to check & remove the checkstyle
errors before doing check-in in the repository.

Datamatics Company Page 30 of 31


Standards – Coding in JAVA

Sr. No. Dont’s


Variable declaration in loop
1.
.size() or .length in loop.
2.

3. Use of e.printstacktrace

4. Use of SOPs

5. Never instantiate Boolean. Use Boolean.TRUE/FALSE

6. Util class should not have any application specific imports.


Instantiate an object multiple times within if-else ladder. If a method is supposed to return an
7. initialized object, instead instantiate it while declaring.
Use <list>.size() method to initialize array while converting into array using toArray() method. Use
8. 0 instead.

9. Multiple variable declaration in one line

10. Use of Vector / HashSet


Multiple/Conplex operations in a single line e.g. a = (a + b++ + c) + d;. Instead split into multiple
11. lines as a = (a + b + c) + d;
b++;

Datamatics Company Page 31 of 31

You might also like