java coding standard

22
Java Coding Standard for Android

Upload: praveen-bhambey

Post on 09-Apr-2016

23 views

Category:

Documents


4 download

DESCRIPTION

Java-Coding-Standard

TRANSCRIPT

Page 1: Java Coding Standard

Java Coding Standard for Android

Page 2: Java Coding Standard

Page 2 of 22

Table of Contents

1 Introduction ............................................................................................. 4

2 Formatting Conventions ......................................................................... 5

2.1 Naming Conventions .......................................................................................... 7

2.2 Basic Test Classes ............................................................................................. 9

2.3 Documentation Conventions ............................................................................... 9

2.4 Additional Comments ........................................................................................ 10

2.5 Commenting out Code ...................................................................................... 11

2.5.1 Production Code ..................................................................................... 11

2.5.2 Test Code ............................................................................................... 11

3 Programming Conventions .................................................................. 12

3.1 Low Coupling High Cohesion ............................................................................ 12

3.2 Class Structure ................................................................................................. 12

3.3 Class and Interface Design ............................................................................... 12

3.4 Dependency Inversion Principle ........................................................................ 13

3.5 Visibility Modifiers ............................................................................................. 13

3.6 Magic Numbers ................................................................................................ 14

3.7 Import Statements ............................................................................................ 14

3.8 TODO tags ....................................................................................................... 14

3.9 Exceptions ........................................................................................................ 15

3.10 Finalize ............................................................................................................. 15

3.11 Boolean Arguments .......................................................................................... 15

3.12 Variable declaration .......................................................................................... 16

3.13 Referencing Constants ..................................................................................... 16

3.14 Cascading Assignment Operators .................................................................... 17

3.15 Assignments in Control Flow Statements .......................................................... 17

3.16 Return types ..................................................................................................... 17

3.17 Number of Return Statements .......................................................................... 18

3.18 Else branch ....................................................................................................... 18

3.19 Instanceof ......................................................................................................... 18

3.20 String literal comparison ................................................................................... 19

3.21 String creation .................................................................................................. 19

3.22 String Concatenation ........................................................................................ 19

3.23 String Comparison ............................................................................................ 20

3.24 Conversion between Byte Arrays and Strings and Vice Versa .......................... 20

Page 3: Java Coding Standard

Page 3 of 22

3.25 Usage of toString() ............................................................................................ 21

3.26 Vectors ............................................................................................................. 21

3.27 Annotations ....................................................................................................... 21

3.28 Boolean creation ............................................................................................... 22

Page 4: Java Coding Standard

Page 4 of 22

1 Introduction While documentation of the high-level design and architecture assists in learning about the overall concept of the software, it does not support the understanding of the low-level details that have been coded. There it is the developer’s task to analyze the existing code.

A Coding Standard helps to keep consistency for the code starting from code layout and extending over naming strategies. Consistent application of coding rules reduces the efforts to read into sources coded by another developer before. In addition to this, code following a consistent style is expected to contain fewer bugs.

This document formulates general principles, recommendations and rules for java coding. The general principles and recommendations cannot and will not be enforced. In contrast, the rules are binding.

For practical reasons code that is reused from prior releases might not be able to comply with these rules. Violations of these rules will not result in defects for such code. However, any modification in such code should adapt the code to compliance with this set of rules.

Page 5: Java Coding Standard

Page 5 of 22

2 Formatting Conventions This section defines the different aspects of the format of a Java source code document. This includes indenting and grouping. Indenting The indention reflects the logical structure of the source code and must be homogeneous to improve readability.

Block Indent RULE: Each inner block code must be indented relative to the outer code block. For indention 4 spaces must be used. Tab chars are not allowed for indenting. Your editor must be configured to interpret Tab chars as 4 spaces.

Control Statements RULE: Control statements must begin in either new line or same line. The two styles must not be mixed.

Example:

try

{

size = inStream.available();

}

// catch statement must begin in new line

catch (IOException e)

{

// handle exception

}

Pros: More readable even without IDE. [Agreed]

or

try {

size = inStream.available();

} catch (IOException e){

// handle exception

}

Pros: Standard followed by Java.

Opening Brackets RULE: An opening bracket always is the last character on a line. Opening brackets must be either one space to the right of the control statement or in a new line at the same indenting level of the control statement. Any other positioning of opening brackets is not allowed. The two styles must not be mixed.

Example:

if (size < currentSize) {

try {

size = inStream.available();

}

catch (IOException e) {

// handle exception

doRecovery();

Page 6: Java Coding Standard

Page 6 of 22

}

}

or

if (size < currentSize)

{

try

{

size = inStream.available();

}

catch (IOException e)

{

// handle exception

doRecovery();

}

}

[Agreed]

Grouping It is recommended to group logically linked statements within the same block visually by separating statement groups by a new line.

Example:

if (isStreamed())

{

if (index > pos)

{

// check bounds

if (reachedEnd)

throw new

ArrayIndexOutOfBoundsException();

if (max != -1 && index >= max)

throw new

ArrayIndexOutOfBoundsException();

// load the objects from the object stream

int fetchSize = index-pos;

super.addAll(stream.nextElements(fetchSize));

// update position, size and reachedEnd flag

if (super.size() < pos + fetchSize)

{

// Ok, we must have reached the end

size = -1;

pos = size;

reachedEnd = true;

stream.close();

stream = null;

}

else

pos += fetchSize;

}

}

Line Breaks

Page 7: Java Coding Standard

Page 7 of 22

It is recommended to limit the length of a single line to 140 characters. This should improve readability of the code. The developers may exceed this limit if they feel the effects of the 140-character limitation are counterproductive for the readability of the code.

Statements that use multiple lines must be indented, e.g.

CustomerOrgNode myCustomerOrgNode =

(CustomerOrgNode) AbstractFactory.readQueryObject(

CustomerOrgNode.class.getName(),

myCoolToplinkExpression);

2.1 Naming Conventions Naming conventions covers package naming, class naming, method naming and field naming conventions. In general, naming conventions for Java include - Starting with small letters

(not for class names) - Use complete words or combinations thereof

- Capitalize the first letter of a joined word, e.g. goToNirvana()

(not for package names) - Try to reflect the semantics in the name - Avoid use of special characters ‘_’, ‘&’, etc. unless they are element of the coding

standard.

- Respect capitalization and joined words also for terms used commonly in upper case, e.g. htmlBang instead of HTMLBang

Package Naming Conventions All packages are prefixed with com.kiplinfo.

- Constant Naming RULE: The names of constants (final field) must consist of capital letters only. Underscores may be used to visually separate name elements, but may not be used as a constant name prefix. Example:

public final static String HELLO_WORLD = “Hello World”;

public void printHelloWorld()

{

System.out.println(HELLO_WORLD);

}

- Variable Naming RULE: Variable naming conventions allow the distinction of the variable scope from its name. The preferred variable naming convention defines patterns for instance variables, class variables and method parameters. Stack local variables use standard java naming conventions.

- Field Naming RULE: All instance variable names (non-static fields) are prefixed with an underscore ‘_’. Otherwise the general naming conventions apply.

Page 8: Java Coding Standard

Page 8 of 22

For class variable names (static fields) the same conventions apply as for instance variable names.

- Method Parameter Naming RULE: All method parameter names are prefixed with the small letter ‘p’. Otherwise the general naming conventions apply. The first letter after the prefix must be capitalized.

- Stack Local Variables Naming RULE: The names of local variables must comply with the general naming conventions. The name must not start with an underscore ‘_’ or a small ‘p’ followed by a capital letter to avoid confusion with one of the above patterns.

Variable names must not contain any type information like

String testString = ”Test”;

Or

Int intValue = 0;

Example:

class Incrementor

{

private int _incrementValue = 1;

public int increment(int pIntValue)

{

int incrementedIntValue = pIntValue + _incrementValue;

return incrementedIntValue;

}

}

Interface Naming Conventions An interface provides a declaration of the services provided by an object, or it provides a description of the capabilities of an object.

Use nouns to name interfaces that act as service declarations:

public interface ActionListener

{

public void actionPerformed(ActionEvent e);

}

Use adjectives to name interfaces that act as descriptions of capabilities.

Most interfaces that describe capabilities use an adjective created by tracking an “able” or “ible” suffix onto the end of the verb:

public interface Runnable

public interface Accessible

Page 9: Java Coding Standard

Page 9 of 22

- Interface Naming RULE: Use nouns or adjectives when naming interfaces.

2.2 Basic Test Classes Basic test classes have to be placed in the same package like the class to be tested but in the test source folder and not in the main source folder.

- Test Class Naming RULE: Basic test classes produced in development work must be post fixed with Test to the class that is tested. The postfix indicates that the class is a test class and it is easier to find it. Example:

Class to be tested:

..src/main/java/com/kiplinfo/core/schema/SchemaCache.java

Test class:

..src/test/java/com/kiplinfo/core/schema/SchemaCacheTest.java

Basic Test Methods - Test Method Naming RULE: The name of a test method must reflect what is tested.

A descriptive name forces the programmer to only test one thing and the reader will easier understand what is to be tested and the expected test result.

2.3 Documentation Conventions The documentation is based upon the Javadoc facilities. Javadoc defines a commenting style, which aims at the automated generation of API documentation, e.g. in HTML or PDF format. The Javadoc standard defines a set of tags for documentation information, like @author, @param, @return, @since, @see and @throws and recognize standard HTML formatting tags within the comments.

The developers are required to provide adequate Javadocs for their source-code. The details of the Javadoc requirements are defined in the sections below. The developers are encouraged to enhance their Javadocs with basic HTML tags to improve the quality of the generated output, but without compromising readability as pure text.

Use @since tag for big changes or features in order to specify the version since the functionality exists. You can use the @link tag to reference Javadoc outside the @see tag.

The developers are also encouraged, but not required, to add further comments in the code, where it seems reasonable.

- Javadoc Format RULE: The lines of any type of Javadocs must not exceed 140 characters length.

- Class Javadoc RULE: Each class must have Javadoc style comments placed directly above the class keyword. The class Javadocs shall describe the semantics and general use of the class and must answer the key questions: Why does it exist, when is it used and what problem does it solve? The @author tag is required.

Page 10: Java Coding Standard

Page 10 of 22

The developers are encouraged, but not required, to include @see tags to link related classes to the Javadocs.

- Method Javadoc RULE: Each method, regardless of its visibility, must have Javadoc style comments placed directly above its definition. The method Javadocs shall describe the semantics and general use of the methods and should include the following tags

A @param tag for each parameter of the method. For generic collection type parameters, e.g. the java.util collection classes, the structure and type of the contained elements should be documented.

A @return tag for methods with non-void return type. For generic collection type return values, e.g. the java.util collection classes, the structure and type of the contained elements should be documented.

A @throws tag for each exception potentially rose within the method body, including RuntimeExceptions. RuntimeExceptions only if thrown in the method itself, but not in methods called from the method.

A @throws tag for each exception declared in the throws clause of the method definition.

The developers are encouraged, but not required, to include @see tags to link related classes and methods to the Javadocs.

- Field Javadoc RULE:

Each field, regardless of its visibility, must have Javadoc style comments placed directly above its declaration. The field Javadoc shall describe the semantics of the content of the field. Especially for collection types and other generic types the field javadoc should contain information about the content type and structure.

The developers should not place any javadoc tags in the field javadocs.

2.4 Additional Comments The developers are encouraged to add further comments directly to the code whenever the semantics are not straightforward. Especially statement groups as described in 0 should be commented. However the comments should be kept as short as possible to avoid ‘pollution’ of the source code. Several rules apply for this type of documentation

Comment Style RULE:

All non-Javadoc comments must use the ‘//’ notation. The ‘/* bla */’ notation should not be used.

Statement Comment RULE:

Comments on statements or statement groups must not use Javadoc notation. They should be placed directly above the statement or statement group they refer to.

Page 11: Java Coding Standard

Page 11 of 22

2.5 Commenting out Code

2.5.1 Production Code

Code should not be comment out when committed. If the code is needed in the future the source control system will remember it.

The reader will not understand why and when the code was commented out and why it is still in. Commented out code will gather and clutter up the code.

In worse case it starts floating away from its initial position making the reader even more confused.

2.5.2 Test Code

Basic test cases that out of some reason does not apply until later should be disabled via i.e. Junit annotation and commented on why it is disabled.

Example:

// The addition function is to be added after blabla

@Test (enabled = false)

public void testThatDaysCanBeAddedToDate()

The test annotation will prevent other developers from removing the code.

Page 12: Java Coding Standard

Page 12 of 22

3 Programming Conventions

3.1 Low Coupling High Cohesion

Smaller classes are easier to overview and comprehend and are likely to focus on only one thing.

High cohesion means classes will be easier to maintain.

Low coupling means classes will be easier to maintain since changes affect fewer classes (minimize interdependency between classes).

This is vital and mandatory if you are going to work with many people on larger projects. Please note that low coupling does not mean that you should avoid reusing objects since this usually just leads to people writing the same type of code in many places.

For instance a piece of code for reading a specific resource (like a text file) that is done often can (and should) be accessed from many other classes provided that it is done in a sensible manner.

RULE:

Classes shall be kept small. Strive for having the code in one class strongly related (high cohesion) and having few relations to other classes (low coupling).

3.2 Class Structure

Class Structure RULE:

A class must be structured in separate areas for field declaration, methods, initializers, inner classes and constructors. The order of these areas is

1. field declaration area

2. static initializer area

3. constructor area

4. method area

5. inner class definition area

The field declarations must be ordered to have all static declarations before the non-static declarations and all final declarations before the non-final declarations.

3.3 Class and Interface Design

Long call chains makes testing more difficult, especially at mocking were the dependencies has to be mocked too. Long call chains also make changes in one part of the system cascade into other parts and thus make the system fragile.

customer.pay(amount);

instead of

customer.getWallet().pay(amount);

Page 13: Java Coding Standard

Page 13 of 22

RULE:

The amount of objects that an object interacts with must be kept low. Interaction should primarily be with immediate references.

3.4 Dependency Inversion Principle

This makes maintenance easier since dependency of implementation details do not affect other classes. By using abstractions, references are easier to use polymorphic and it is possible to change implementation during runtime. If the concrete implementation is used in method signatures for abstract/super-classes and interfaces the problem of changing implementation will spill over to the implementing classes.

Example:

List<RatingDecimal> theResult = new

ArrayList<RatingDecimal>();

public Map<Short, Job> getAllJobs(List<Short>

dentifiers)

Bad example:

ArrayList<RatingDecimal> theResult = new

ArrayList<RatingDecimal>();

public HashMap getAllData(Vector identifiers)

RULE:

Depend on abstractions instead of concrete implementations and never allow abstractions to depend on details.

3.5 Visibility Modifiers

It is very important to make use of the visibility features offered by the Java language. A developer should clearly distinguish between private, protected, public and package private access when designing classes, methods or constants. The callers should only see and have access to the minimum set of functionality. This reduces complexity for the users of the class and also reduces the chances of defects and misuse. For instance and class variables the following rule applies.

Variable Visibility RULE:

Instance and class variables must be private. If their values should be available to the outside, provide access methods with adequate visibility.

Page 14: Java Coding Standard

Page 14 of 22

3.6 Magic Numbers

Literal ordinal constants embedded within source should almost never be used. Whenever possible, use constants instead of literal ordinal constants. The reasons for this are twofold. First, an update to the number can be done in a single place instead of being distributed in your code. Second, a meaningful name can clarify the meaning of a number. Consider this example:

static final int DAYS_IN_WEEK=7; // explicit description!

int totalDays = 10 * DAYS_IN_WEEK; // what is 10 about?

Magic Numbers RULE:

Whenever possible, avoid magic numbers.

3.7 Import Statements

It is the decision of the developer, whether to use package imports or type imports. As a rule of thumb, if more than three types have to be imported from a package, the import of the package is clearer than importing of each single type.

Import Statement Guideline:

The import statements must be placed after the disclaimer and before the class Javadocs. They should be ordered by import groups, e.g. JDK packages and TOPLink packages, and should be ordered alphabetically within those groups.

3.8 TODO tags If a developer does not have a solution for a coding problem, or identifies potential problems in the code a to-do tag should be placed in the Javadocs. The format of a to-

do tag is @todo <name> <problem description>. The name should make it

easy to find the author of the TODO tag and has to be followed by a detailed description of what the reason for that to-do is and potential solutions. Example: /**

* Trigger explicit validation of the objects managed within the

* TransactionContext.

*

* @todo Ashish Goyal add error codes to exception.

*/

public void validateI() throws ValidationException

{

try

{

validatePhase();

}

catch (ApplicationException e)

{

ErrorDictionary.throwValidationException(

"NN",

this,

null,

Page 15: Java Coding Standard

Page 15 of 22

null,

e);

}

3.9 Exceptions

Exception RULE:

Do not eat up exceptions. Avoid for example: try {

.... something that throws exception

}

catch (Exception e) {

}

Explain why the exception is catched and does not throw it again. At least comment, why the exception is not considered any longer.

If the method signature does not fit the catched exception convert the original exception to the exception in the signature.

If exception is used as error condition, it should be considered to change the behavior from returning a boolean instead of throwing an exception.

Log the exception

3.10 Finalize

Finalize method RULE:

Do not rely on the usage of finalize, it might not even be called. Use the following pattern, if not directly inherited from Object.

protected void finalize() throws Throwable

{

try

{

// clean up related to the current class

}

finally

{

// force finalize of super class

super.finalize();

}

}

3.11 Boolean Arguments

Boolean arguments indicate that the method does more than one thing. Therefore Boolean arguments should be avoided for public methods. Split the method into two dedicated independent methods that could be called without using the flag.

Example:

public void close()

Page 16: Java Coding Standard

Page 16 of 22

public void closeAndRemove()

Bad example:

public void close(boolean removeFile)

3.12 Variable declaration

Each variable should be declared individually on a separate line. This convention enhances readability.

Example:

String logicalName = getName();

Bad examples:

int id1, originalId1;

int id2 = 0, originalId2 = 0;

It is recommend declaring variable type as late as possible and not declaring all types at the beginning of a method like in C. This helps the virtual machine optimizing the execution.

public void myMethod()

{

int i= 0;

String lMyString = null;

...

i = 1;

lMyString callAnyMethod(i);

}

Instead, declare all types as late as possible:

public void myMethod()

{

...

int i = 1;

String lMyString callAnyMethod(i);

}

A local variable should be used for one thing only, i.e. do not reuse it. A small scope and prevention of local variable reuse increase the possibility that a variable is initialized correctly.

3.13 Referencing Constants

Referencing public static constant RULE:

A public static constant must be referred to via its class name, not through an instance variable. Referencing on correct level increases the possibility to understand the code and prevents error due to shadowing.

Example:

exit = java.swing.JFrame.EXIT_ON_CLOSE;

Page 17: Java Coding Standard

Page 17 of 22

Bad example:

JFrame frame = new JFrame();

exit = frame.EXIT_ON_CLOSE;

3.14 Cascading Assignment Operators

One assignment per statement RULE:

Cascaded assignments are difficult to read. Therefore make only one assignment per statement.

Bad example:

id = originalId = 0;

3.15 Assignments in Control Flow Statements

An assignment operator is easily confused with the equality operator if the latter is expected. Therefore the assignment operator should not be used where it can be confused with the equality operator.

Bad examples:

if (isStarted = currentStep == ONGOING)

{

. . .

}

while (isStarted = lastState)

{

. . .

}

3.16 Return types

Collection return type RULE

For methods that return an array or a collection of object, do not return null to signify an empty list. Instead return an empty array or collection.

Array example: public Product[] getProducts()

{

...

// nothing found

return new Product[0];

}

Or better static final NULL_PRODUCT_ARRAY = new Product[0];

public Product[] getProducts()

Page 18: Java Coding Standard

Page 18 of 22

{

...

// nothing found

return NULL_PRODUCT_ARRAY;

}

Collections example: public List<Product> getProducts()

{

...

// nothing found

return Collections.emptyList();

}

3.17 Number of Return Statements

Too many return statements make a method more difficult to read and to refactor. Early termination due to easily-checked faults removes need for nested conditions.

Try to limit the number of return statements in a method. Consider using a local variable to temporarily keep the result until a return can be made. For simple decisions the ternary operator can be used.

Code readability takes precedence over this rule, so it is acceptable to have multiple returns, for example to trigger early execution termination or to avoid excessive nesting.

3.18 Else branch

For else branches it is recommended to use always brackets for else branches.

Instead of if

{

}

else

throw new Exception()..

Use if

{

}

else

{

throw new Exception();

}

This avoids errors if e.g. a log is added before the throw clause.

3.19 Instanceof

It is recommended for an instanceof construct like

if (ado != null && ado instanceof SPHistoryI)

To drop the “ado !=null” check. The check for “!= null” is not needed, since null does never fulfill instanceof condition. Therefore

if (ado instanceof SPHistoryI)

Page 19: Java Coding Standard

Page 19 of 22

can be used directly.

3.20 String literal comparison

String literal comparison RULE:

For string comparison instead of

(_aString.equals("X")?true:false);

the construct

"X".equals(_aString);

must be used. The ordering will prevent null pointer exceptions.

The same applies if a constant String value is used in the comparison like

static final String PRODUCT_TYPE = “CST”;

…..

if (PRODUCT_TYPE.equals(_aString)) ….

3.21 String creation

String creation RULE:

It is normally never necessary to do something like this

String testValue = new String(“Test”);

Instead the string creation can be avoided by

String testValue = “Test”;

3.22 String Concatenation

String concatenation RULE:

Concatenation of String can be done with + or += if the string concatenation can be completed by a single statement. String concatenation using + is replaced with

StringBuilder by the Java compiler. This works well in most cases, but can lead to

unnecessary object creation if multiple statements are necessary to complete the string concatenation as shown in the following example:

String result = "No data found for " + title;

If (fieldFound)

{

result += " and field " + fieldName;

}

In such cases the StringBuilder must be used instead:

Page 20: Java Coding Standard

Page 20 of 22

StringBuilder tempResult = new StringBuilder();

tempResult.append("No data found for ").append(title);

If (fieldFound)

{

tempResult.append(" and field ").append(fieldName);

}

String result = tempResult.toString();

String.format() should not be used: String.format(), as almost all other

String manipulation methods (with exception of substring()), may cause bad

performance due to extensive internal copying of data.

StringBuffer must be used when concurrent access of different threads on the

same object is required as the StringBuilder is not thread safe.

3.23 String Comparison

When comparing a String variable with a String constant, the String constant should be the object to which the comparison is done.

Example:

boolean isFound = "Field1".equals(aField);

If the recommended way of comparing is followed the statement will evaluate to false

instead of throwing a NullPointerException when the field to compare (aField in

the example) equals null.

3.24 Conversion between Byte Arrays and Strings and Vice Versa

When converting between byte arrays and Strings (using String constructor) and vice versa (using getBytes method) a charset should be explicitly stated.

The charset to use depends on where in the node the conversion is done: xml files usually states format to use.

In general these conversions are costly since the conversion invokes lots of coders/decoders and should be avoided if possible but when needed, this convention should be followed.

When making the conversion without specifying a character set to use, the default character set of the machine is used. This may give unpredictable behaviour and subtle errors.

Example:

String id = new String(bytesIn, "UTF-8");

byte[] encodedId = id. getBytes("UTF-8");

Bad example:

Page 21: Java Coding Standard

Page 21 of 22

String id = new String(bytesIn);

byte[] encodedId = id. getBytes();

3.25 Usage of toString()

The method toString is used by debuggers to get a readable text version of an

object. The method toString may be changed at any time to provide more

information in the debugger. This should not affect any implementation details. So a

custom implementation of toString should never be used except for debug

purposes.

Example:

StringBuilder builder = new StringBuilder("This is a

string");

return builder.toString(); // This is ok. Not a custom

impl.

// Implicit call to toString is ok because this is only

for debug

if (DEBUG) LOG.debug("Doing something with my object: " +

myObj)

3.26 Vectors

All methods that access the Vector class instance data are synchronized. This policy imposes a high price in performance for the clients of these classes, which is true whether they need thread safety or not. Vector and its subclasses should not be used. If a synchronized collection is really needed, then use the Collection most appropriate for your need and then make it synchronized by applying a synchronization wrapper from Collections.

Example:

List<Job> mySynchronizedJobListList =

Collections.synchronizedList(new ArrayList<Job>())

3.27 Annotations

The @Override annotation should be used on every method declaration that is

thought to override a superclass declaration. This convention helps avoiding unintentional overloading and warns when a superclass method signature has changed.

The annotation @SuppressWarnings should not be used. Eliminate the warning by

changing the code. There are situations when the annotations could be used, such as when using a third party library that generates warnings when used as intended. In

these cases the @SuppressWarnings annotation should have the smallest possible

scope and a comment should be given about why the annotation had to be used. Warnings are indications of potential problems and faults and should be acted upon.

Page 22: Java Coding Standard

Page 22 of 22

Using this annotation should not be an easy way to eliminate the indication without acting on the problem.

3.28 Boolean creation

Do not create a Boolean object using the new() operator.

It is never necessary to do something like this

Boolean myValue= new Boolean(true);

Instead the boolean creation can be avoided by

Boolean myValue= Boolean.TRUE;

In case a Boolean object has to be created from a simple Boolean type the construct must be used. The usage of the Boolean constants avoids many unnecessary object creations

Boolean lValue= Boolean.valueOf(simpleBooleanValue);