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

S.No. Descriptions Arrays: Only in Reasonable Cases (E.g. Too Many Casts Would Have Been Necessary)

To simplify usage of arrays and prevent NullPointerExceptions, the ArrayUtils class from Apache Commons is used. Entities using arrays should declare empty array constants to avoid creating empty arrays repeatedly. For timestamps in logging, the UTCFormatter format method is called. Interfaces rather than implementations should be used for variable declarations where possible. The @Override annotation should mark overridden methods.

Uploaded by

Surinder Singh
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

S.No. Descriptions Arrays: Only in Reasonable Cases (E.g. Too Many Casts Would Have Been Necessary)

To simplify usage of arrays and prevent NullPointerExceptions, the ArrayUtils class from Apache Commons is used. Entities using arrays should declare empty array constants to avoid creating empty arrays repeatedly. For timestamps in logging, the UTCFormatter format method is called. Interfaces rather than implementations should be used for variable declarations where possible. The @Override annotation should mark overridden methods.

Uploaded by

Surinder Singh
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 18

S.No.

Descriptions
ARRAYS
1 To simplify the usage of arrays and to reduce errors the
class org.apache.commons.lang3.ArrayUtils from Apache
Commons is used.
Its methods are null safe. Therefore
NullPointerExceptions are prevented

2 Entities which are using arrays must declare a constant


for an empty array. These constant will be used in
methods which return an empty array. Therefore an
empty array must not be created all the time and garbage
collector has less work to do.

COMMONS
3 To prepare a timestamp for logging the method
com.forcam.na.logging.UTCFormatter.format() must be
called. The timestamp will be displayed in a readable
format with UTC-value then

4 For variable declarations always use the interface not the


implementation (e.g. List instead of ArrayList). Exceptions
only in reasonable cases (e.g. too many casts would have
been necessary)

5 Add the @Override annotation to mark overridden


methods (e.g. equals() or toString() method).
6 When unboxing objects, be aware of null case. A
NullPointerException might be caused

7 Declaration of generics was simplyfied in Java 7. Therefor


the diamond operation (<>) was introduced

8 For returning empty lists, maps or sets use these calls to


the Collections class.
he returned empty map, list and set are unmodifiable.
The advantage of these methods is, that each call don't
create a new object and this results in a lower memory
consumption.

9 Divisions and modulo operations must not result in a


divide-by-zero error. This is an example for a correct
division

10 There must be no comparison with NaN (not a number) ,


because every comparison will result in false. This
example reveals the error:
11 Avoid casting as far as possible. Use generics to be type
safe.
12 Finalizer must not be implemented because their
behavior is not predictable.

Concurrency & Distributes Computing


13 To get a map for concurrent access it is not allowed to
use java.util.concurrent.ConcurrentHashMap, instead
methods from java.utils.Collections must be used. This is
because ConcurrentHashMap is providing no reliability
regarding data consistency.

14 Always try to optimize the single threaded algorithm first


before parallizing it.

DATABASE
15 Access on the database must be performed via JPA
repositories or via DAOs
16 DAOs will be used if the HQL statement needs to be build
dynamically or there is post processing required for the
results of the query.
17 If someone is making changes on Database objects
through JPA classes i.e. Creating a Table, Indexes,
Constraints or Altering the objects Respective DDL sql
statements should also be added in migrate folder of
DDL_COMMON directory with appropriate file name
conventions followed by FORCAM. Special care must be
practiced to write a DDL statement which is applicable
both for Oracle & SQL Server Database.

18 Please always keep in mind that the column names of the


tables should always be in upper case if you are creating
it through JPA classes or whether manually writing in .sql
files. The same should always be followed when writing
sql queries in your code

Exceptions
19 Exceptions are logged with the method
com.forcam.na.common.LogUtilities.logError(). This
method logs the first 10 exceptions of exception
hierarchy of the stacktrace.

20 Inside a catch-block no writing must be done to the


stdout or stderr stream. System.out.print*(),
System.err.print*() or Throwable.printStackTrace() are not
allowed

21 If several exception types are catched it can be done by


an exception list.
Based on this the Java-Compiler generates better
bytecode.

22 A finally-block must not be exited abruptly. This means


no return, break, continue or throw statement is allowed
inside a finally-block. If finally-block code throws
exceptions they must be catched. The following class
suppresses a RuntimeException which is not be thrown
because a return statements exists in the finally-block.

23 No exception must be thrown in a finally-block which is


not catched inside the finally-block. Otherwise it will lead
to an an abrupt exit of the finally-block.
FORMATING
24 For if, else, for, do and while there will be used brackets
all the time - even when the body contains only one line.

25 Each variable declaration will be placed in an extra line.


Declarations like String a, b, c; are not allowed
26 No C-Style for array declarations: String[] a, but not String
a[].
27 If there is no break in a case statement, then a
commentary is needed to explain why it is required.
Commentary „// fall through“ needs to be added.
28 Every switch statement must have a default at its end -
even when it will not contain any code
29 Annotations are placed directly over the class name
30 One annotation per code line. e.g. @Override @Column
in one code line is not allowed
Java Doc
31 All comments have to be written in english language
32 This header contains perforce variables which will be
replace with values when the class is submitted. This
header is configured in the file and code templates for
Java in IntelliJ Idea
33 This header contains perforce variables ($$Id) which will
be replaced with values when the class is submitted. This
header is configured in the file and code templates for
Java in IntelliJ Idea. After importing the settings.jar in
IntelliJ Idea, the user have to fit the header with his name
and email address

34 Each constant, member variable, constructor, method


and getter/setter must have a javadoc description. For
constants and member variable please use a one line
comment

35 Don't separate the variable name and the variable


description with a - or other separators. IntelliJ Idea is
automatically format the JavaDoc

36 Give a description of the return value and not the type

37 Use correct spelling in the JavaDoc comments. Start with


capital letter and use . at the end.
38 When you refer to constants, classes or methods of a
class or interface, use the link tag to link directly to the
class.

39 When you refer to variable name or other Java keywords


use the code tag to mark this value.

Naming
40 Identifiers (names of classes, interfaces, enumerations,
methods, parameters and variables) must not be
random. The name of an identifier has to be composed in
such a way that they carry meaningful information about
their purpose and their role in the code. This makes the
code easier to read and understand

41 Variable naming

42 Classe names are written in UpperCamelCase


43 If a class name contains a common abbreviation, then it
is allowed to use upper case for the whole abbreviation
44 The is prefix should be used for boolean variables and
methods
45 Interface names have to be started with an I and consist
of a noun and possibly a few adjectives
46 Constants are written in capital letters. Words will be
seperated by _
Object Class Overrides
47 Every entity must override equals() and hashCode() to be
processed correctly by classes from java.util (Listen,
Maps, Sets).
48 The equals() method must fullfill these requirements:

49 All fields must be used in an equals() method which are


relevant for the object's identity. Static variables must not
be used because they are same for all objects of the
particular type. The same is valid for transient variables.

50 Entities with an unique id can be compared by the id.


Attention: If the id is created by Hibernate then the id will
be only set after saving the entity. If unsaved entities are
used in lists, maps or sets then other data of the entity
must be used for equals().

51 For comparison only immutable objects must be used.


Otherwise it will lead to inconsistent states of sets and
maps.
52 Entities must overide toString() method to be able to
print its content.
Resource Management
53 All resources which have been opened must be closed
again. This must be done in a finally block if possible
because resources must also be closed in case of an
exception.

54 Now the exceptions are caught and it is ensured that all


streams will be closed. Unfortunatley there is a lot of
boilerplate code in the finally-block left. It is not easy to
read the code. To prevent this IOUtils.closeQuietly() can
be used to close the streams.

55 Use AutoCloseable features of Java 7 to close the


resource.
56 UTF-8 must be declared for encoding always while
reading and writing from/into streams. Always check
methods of IOUtils before handling streams manually

57 To simplify the usage of streams and to reduce errors the


class org.apache.commons.io.FileUtils from Apache
Commons is used. Always check methods of FileUtils
before handling files manually

Spring/Services
58 The name of the service must always be declared in the
annotation for the service. Normally it is the class name
(e.g. @Service("AlarmingService")).
59 The class and/or interface of a service has to be fully
documented with JavaDoc. The following point are
important:

60 If classes retrieve and return mutable objects they must


ensure that the modification of theses object will have no
impact on the state of the class.
61 Service methods must be marked with @Transactional
only if it really wants to acces the database. It's only
allowed to mark the whole service with @Transactional if
every method of the service is accessing the database in
the same way (read or writable transaction). There is a
difference for transactions which are reading from the
database and for transactions which are actually writing

62 All classes, interfaces an enumerations for a service must


be placed in the same package or subpackage like the
service
63 Utlility classes must be declared as final and must have a
private constructor. All methods must be declared as
static.

64 Parameters of public methods must be validated with


com.forcam.na.common.Validator. The service must not
change into an undefined state. If the parameters do not
satisfy the requirements the Validator will throw
NullPointerException and IllegalArgumentExceptions.
These are the most important methods of the Validator
class

Strings
65 To simplify the usage of Strings and to reduce errors
org.apache.commons.lang3.StringUtils from Apache
Commons should be used. Methods of StringUtils must
be checked before manipulating strings manually.
Its methods are null safe. Therefore
NullPointerExceptions are prevented

66 For empty string use the constant StringUtils.EMPTY.


67 For concatenation StringBuilder must be used. The class
StringBuffer is synchronized and therefore not as fast as
StringBuilder.
68 Inside the append() methods of the StringBuilder the +
Operator must not be used to concatenate strings.
Always use append()
69 If it is possible to estimate the maximum size of the string
the StringBuilder will always be initialized with a buffer
size. This is important, because StringBuilder uses an
array internally. If the size of the array is overrun a new
array with double size will be created and content of the
old array will be copied into the new array. This is time-
consuming and therefore should be prevented.
Examples
ARRAYS
1. contains() => Checks if an element is contained by an array. If there is no element in the array
ArrayUtils.INDEX_NOT_FOUND will be returned.
getLength() => Delivers the length of the array. If null is passed 0 will be returned.
2. indexOf() => Delivers the index of an element in the array. If the element is not found the constant
ArrayUtils.INDEX_NOT_FOUND will be returned.
3. isEmpty() => Indicates if the array is empty. If null is passed true will be returned.
4. subarray() => Delivers parts of an array.
5. toObject() => Converts an array with primitive types into objects.
6. toPrimitive() => Converts an array of objects into primitives.
7. toString() => Creates a string from the content of an arry. null is handled in the same way like an empty array.

public class Entity {


public static final Entity[] EMPTY_ARRAY = new Entity[0];
}

public class Task {


public Entity[] doSomething() {
...
...
return Entity.EMPTY_ARRAY;
}

public Entity[] doSomethingSpecial() {


...
List<Entity> list = mEntityRepository.findAll();
return (list.isEmpty() ? Entity.EMPTY_ARRAY : list.toArray(new Entity[list.size()]);
}
}

COMMONS
public class ValueContainer {
public Long getValue() {
return null;
}
}
public class Sample {

private ValueContainer mContainer = new ValueContainer();

public long getValue() {


final Long value = mContainer.getValue();
return (value == null ? 0 : value);
}
}

Before:
List<String> listStrings = new ArrayList<String>();
List<Map<String, List<String>> listMapStrings = new ArrayList<Map<String, List<String>>();

After:
List<String> listStrings = new ArrayList<>();
List<Map<String, List<String>> listMapStrings = new ArrayList<>();

1. empty Map: org.apache.commons.collections.MapUtils.EMPTY_MAP and


org.apache.commons.collections.MapUtils.EMPTY_SORTED_MAP.
2. empty List: org.apache.commons.collections.ListUtils.EMPTY_LIST.
3. empty Set: org.apache.commons.collections.SetUtils.EMPTY_SET and
org.apache.commons.collections.SetUtils.EMPTY_SORTED_SET.

long number1, number2, result;


...
if (number2 == 0) {
// Handle error
} else {
result = number1 / number2;
}

Before:
double x = 0.0;
double result = Math.cos(1 / x); // Returns NaN if input is infinity
if (result == Double.NaN) { // Is always false
System.out.println("result is NaN");
}

After:
double x = 0.0;
double result = Math.cos(1 / x); // Returns NaN if input is infinity
if (Double.isNaN(result)) {
System.out.println("result is NaN");
}
These problems come up with finalizers:
1. There is no definitely time when the finalizer will be executed.
2. There is no guarantee that all finalizer will be called on shutdown of the jvm. The same applies for calling
methods like System.gc(), System.runFinalization(), System.runFinalizersOnExit() and
Runtime.runFinalizersOnExit(). Some of these methods have already been marked as deprecated and must not be
used to prevent security risks and deadlocks.
3. There is no definitely processing order for finalizer methods.
4. Uncatched exceptions during execution of a finalizer will be ignored.
5. Usage of synchronization mechanism may lead to deadlocks.

Concurrency & Distributes Computing


Please use the following methods to get synchronized collections:
1. synchronizedCollection
2. synchronizedList
3. synchronizedMap
4. synchronizedSet
5. synchronizedSortedMap
6. synchronizedSortedSet

The parallelization of jobs must only be implemented through one of these frameworks:
1. Akka (preferred for communication inside an application, http://akka.io/docs/):
2. Quartz (for scheduled jobs, http://quartz-scheduler.org/documentation)
3. JMS (preferred for communication between applications)
Akka provides an easier and much more robust and scalable approach than java.util.concurrent.

DATABASE

Exceptions
catch (IOException | SQLException ex) {
LOGGER.log(ex);
}

FORMATING

Java Doc
Invalid
/**
* <some description>
*
* @param parameter1 - <description of parameter 1>
* @param parameter2 - <description of parameter 2>
*/

Incorrect: Correct:
/** /**
* <some description> * <some description>
* *
* @return String * @return <return value description>
*/ */

/**
* This is a comment with a link to the {@link Workplace} class.
* Also a link to a method {@link Workplace#toString()} or constant {@link Constants#UTF_8}.
*/

/**
* This is a {@code null} value. Other samples, {@code true}, {@code false}.
* Here is markup of the member variable {@code mValue}.
*/
Naming
Good name are: SAPDownload, fileContent, mDateFormat.
Bad names are: a, a1, x55, refx, button1

1. Member variables of classes contain suffix m.


2. All member variables need to be declared as private. Variables must be only accessed through getter/setter
methods.
3. Is there a private inner class, it will be allowed to acces member variables directly.
4. Local variables do not have a suffix like member variables.
5. Generic variables should have the same name as their type.
e.g.: TicketAdministrationService, WorkplaceConfiguration
e.g. HTMLReader.

isSet, isVisible, isClosed

Good names: IContent, IFormattable, ICommandExecutor


Bad names: List, IMemoryOptimize, Ifast
e.g. ENCODING_UTF8.

Object Class Overrides

1. reflexity: the object must be equal to itself, e.g.: a.equals(a) must be true.
2. symmetry: If two objects are equal this must be valid for both directions, e.g.: if a.equals(b) is true then
b.equals(a) must also be true.
3. transitivity: If one object equals to two other objects then the two other objects must also be equal, e.g. if
a.equals(b) and b.equals(c) is true then a.equals(c) must also be true.
4. not null: An object must not be null null, e.g. a.equals(null) must always be false.

public class IntegerPair {


private int mLeft;
private int mRight;

@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o == null) {
return false;
} else if (getClass() != o.getClass()) {
return false;
} else {
Pair pair = (Pair) o;
return (mLeft == pair.mLeft && mRight == pair.mRight);
}
}
}

@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append(...).append(...).toString();
}
Resource Management
Many close() methods do throw exceptions, too. These exceptions must be catched also. No exception must be
thrown out of a finally block

finally {
IOUtils.closeQuietly(dos1); //DataOutputStream dos1 = null;
IOUtils.closeQuietly(dos2); //DataOutputStream dos2 = null;
}

1. closeQuietly() => Closes a stream without throwing exceptions in case of failure.


2. copy() => Copies the content of a stream into another one.
3. readLines() => Reads the content of a stream and returns a list of strings.
4. toByteArray() => Reads the content of a stream and returns an array of bytes.
5. toString() => Reads the content of a stream and returns a string.

1. copyDirectory() => Copies the content of a directory to another path.


2. deleteDirectory() => Deletes a directory recursivly.
3. deleteQuietly() => Deletes a file/directory. In case of failure no exception will be thrown instead of this a flag
will be returned which indicates if the action was successful.
4. listFiles() => Retrieves a list of file if a directory. A filter can be declared for list creation.
5. readFileToByteArray() => Delivers the content of a file as byte array.
6. readFileToString() => Delivers the content of a file as string.
7. readLines() => Delivers the content of a file as a list of strings.
8. writeByteArrayToFile() => Writes the content of a byte array into a file.
9. writeStringToFile() => Saves a string to a file.

Spring/Services

1. A complete description of the service and his functionality.


2. Every parameters has to be descriped. If the parameter can be null then mention this in the description.
Normally a null value can cause in a NullPointerException.
3. If a method returns a null value, then this has to be mentioned in the description. Null may be returned only if
there are important reasons for this. Prefer empty string, empty array, empty list/set/map and so on. This prevent
NullPointerExceptions (please have a look into the capters for strings and arrays).

http://jiravm:8090/pages/viewpage.action?pageId=93225156
1. For writing:
@Transactional(rollBackFor = Throwable.class)

2. For Reading:
@Transactional(rollBackFor = Throwable.class, readOnly = true)

public final class Utility {

/** Avoid instantiation. */


private Utility() {}

public static void doSomething() {


// do something
}
}

1. notNull() => Will throw a NullPointerException, if parameter is null.


2. notEmpty() => Will throw a NullPointerException, if null is passed. If the passed string or array is empty
IllegalArgumentException will be thrown.
3. length() => Will throw a NullPointerException, if null is passed. If the length of the passed string is not in the
defined range IllegalArgumentException will be thrown.
4. range() => Will throw IllegalArgumentException, if a number is not in the defined range.

Strings
1. isEmpty() => Checks if string is null or empty.
2. trim() => Removes whitespace at the beginning and at the end of Strings.
3. equals() => Compares two strings null safe.
4. startsWith() => checks null safe if the string starts with a certain prefix.
5. substring()/left()/right()/middle() => Retrieves null safe parts of a String.
6. split()/join() => Splits a string into substrings respectivley merges them together.
7. defaultString() => Delivers the default string, if null is passed.
8. replaceOnce() => Replaces a part of a string with another string.
9. indexOf() => Finds the index of a substring in a string. If the substring is not found the value
StringUtils.INDEX_NOT_FOUND will be returned.

You might also like