Java_Programming_Guidelines_v2.0
Java_Programming_Guidelines_v2.0
Java
Programming
Guidelines for
PF Projects
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
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.
• The use of these guidelines should result in readable code and should encourage adher-
ence.
• 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.
• 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.
1.4 References
[Sun97] Sun Microsystems: Java Code Conventions.
http://java.sun.com/docs/codeconv/index.html
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.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.
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.
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.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
Rationale
They are almost always typos. The java compiler catches cases where ``='' should have
been ``=='' except when the variable is a boolean.
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.
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.
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.
3 Naming conventions
3.1 General Naming Conventions
Rationale
Type names provide the main glossary and conceptual skeleton for any OO system.
Rationale
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.
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.
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.
Rationale
This makes understanding operations easier and supports precisely describing new func-
tionality. These benefits become especially important as a system grows.
The following is an example subset of the standard meanings for operation name parts and
operation categories (see the Source code format section below).
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.
Prefixes Description
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.
Rationale
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:
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’.
These categories should align with and reinforce operation naming patterns.
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).
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,
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.
Type Identifier
Character c
Index i, j, k
Counter m, n
Object o, obj
Exception e, ex
String s, str
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.
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.
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):
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:
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
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).
• 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.
if (condition)
{
int count; // AVOID
...
}
}
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.
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
} }
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:
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.
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.
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).
10 Constructor They are grouped based on their scope (from the most
general to the most restrictive).
⌦ 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
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.
/**
* <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
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.
@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
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 2: findCmsCode (in Journal service) would have the following namespace:
journal.cmsCode
findCmsJournalById (in Journal service) would have the following namespace: jour-
nal.cmsJournal
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>
<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
<service-name>.<method-specific-keyword>.<provider-method-name>.fullResult.
Datamatics Company Page 25 of 31
Standards – Coding in JAVA
<TypeName>To<ObjectName>TypeHandlerCallback
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.
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.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.
Eclipse_Plugin_Namin
g_Conventions.doc
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.
NAPF_Checkstyle.xm
l
3. Class description with version should be present in all the java classes.
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.
11. Use interface in declarations and method arguments (e.g. List myList and not ArrayList myList).
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
3. Use of e.printstacktrace
4. Use of SOPs