Java Developer Tools

CodePro Audit Rule Set

/h1>

Potential Errors and Refactorings

Powered by CodePro and Eclipse


Summary

Abstract Specialization
Add Method to Interface
Append String
Assignment In Condition
Block Depth
Caught Exceptions
Check Type In Equals
Clone Method Usage
Command Execution
Convert Class to Interface
Dangling Else
Declare As Interface
Declared Exceptions
Default Not Last in Switch
Define Initial Capacity
Disallow Native Methods
Disallow Notify Usage
Disallow Sleep Inside While
Disallow ThreadGroup Usage
Disallow Use of AWT Peer Classes
Disallow Use of Deprecated Thread Methods
Disallow Yield Usage
Duplicate Property Name
Duplicate Property Value
Efficient Expression
Empty Catch Clause
Empty Finally Clause
Empty Statement
Empty Synchronized Statement
Enforce Singleton Property with Private Constructor
Entry Point Method
Environment Variable Access
Equality Test with Boolean Literal
Expression Evaluation
Extra Semicolon
Finalize Method Definition
Float Comparison
Hiding Inherited Fields
Hiding Inherited Static Methods
Instance Field Security
Instance Field Visibility
Invoke super.finalize() from finalize()
Large Number of Parameters
Large Number of Switch Statement Cases
Loss of Precision in Cast
Method Chain Length
Missing Block
Missing Default in Switch
No Run Method
Non-blank Final Instance Field
Non-case Label in Switch
Non-private Constructor in Static Type
Non-protected Constructor in Abstract Type
Non-terminated Case Clause
Obey General Contract of Equals
Overloaded Methods
Override both equals() and hashCode()
Overriding a Non-abstract Method with an Abstract Method
Overriding a Synchronized Method with a Non-synchronized Method
Overriding Private Method
Parenthesize Condition in Conditional Operator
Platform Specific Line Separator
Preferred Expression
Questionable Assignment
Redundant Assignment
Restricted Superclasses
Rethrown Exceptions
Return in Finally
Reusable Immutables
Serializable Usage
Static Field Security
String Comparison
String Concatenation in Loop
String Created from Literal
Synchronized Method
Temporary Object Creation
Throw in Finally
Thrown Exceptions
Type Depth
Unnecessary "instanceof" Test
Unnecessary Return Statement Parentheses
Unnecessary Type Cast
Use "for" Loops Instead of "while" Loops
Use charAt() Rather Than startsWith()
Use equals() Rather Than ==
Use of "instanceof" with "this"
Variable Declared Within a Loop
Variable Should Be Final
Variable Usage
Wait Inside While
White Space Before Property Name
Wrong Integer Type Suffix

Details

Abstract Specialization

Severity: Medium

Summary

Abstract classes should not be subclasses of concrete classes.

Description

This audit rule finds abstract classes that are subclasses of concrete classes. An exception is made for abstract subclasses of the class java.lang.Object.

Example

The following class declaration would be flagged as a violation because the class java.util.ArrayList is not an abstract class:

public abstract class SpecializedList extends ArrayList

while the following class declaration would not be flagged because the class java.lang.Object is treated specially:

public abstract Person extends Object

Add Method to Interface

Severity: Medium

Summary

Identify properties that can be added to an interface.

Description

This audit rule finds methods in concrete classes that can be added to their corresponding interfaces. If a class is named Foo and has a "bar" property with getBar() and setBar() methods, the corresponding interface, IFoo, will be checked to see if it defines the getter and setter method.

Example

If the class Employee were defined as:

public class Employee implements IEmployee

and defined the methods getSSN() and setSSN() that were not declared in the IEmployee interface, then those methods would be flagged as violations.

Append String

Severity: Medium

Summary

Appending strings with single characters to buffers or streams is slower than appending just the single character.

Description

This audit rule finds single character string literals as a single argument to a method invocation where that argument can be replaced by a character literal to improve performance.

Example

Given the following declaration:

StringBuffer sb = new StringBuffer();

The statement

sb.append("a");

would be flagged as needing to be replaced by the statement

sb.append('a');

Assignment In Condition

Severity: Medium

Summary

The assigment operator should never be used in a condition.

Description

This audit rule finds places in the code where an assignment operator is used within a condition associated with an if, for, while or do statement. Such uses are often caused by mistyping a single equal (=) where a double equal (==) was intended.

Example

if (a = 0) { ... }

Block Depth

Severity: Medium

Summary

Methods should be kept fairly flat.

Description

This audit rule finds methods and constructors that have too many levels of nested blocks. A method with too many levels of nested blocks can be difficult to understand. The definition of "too many" can be set.

Example

If the limit is set to two, then the inner if statement in the following would be flagged as a violation:

if (firstChoice == null) { if (secondChoice == null) { if (thirdChoice == null) { return null; } } }

Caught Exceptions

Severity: Medium

Summary

Some exceptions should not be caught.

Description

This audit rule finds catch clauses that catch an exception class that is disallowed. The list initially includes exception classes that are either too general (such as Throwable or Exception), or that are unchecked (such as Error and RuntimeException).

Example

The following catch clause would be flagged because it catches instances of the class java.lang.Throwable, which is too general:

try { ... } catch (Throwable exception) { ... }

Check Type In Equals

Severity: Medium

Summary

Implementations of equals() should check the type of the parameter.

Description

This audit rule finds implementations of the method equals() that do not check the type of the parameter. The rule can be configured for how the type of the parameter should be checked.

Example

The following declaration of the equals() method would be flagged because the type of the argument is not checked:

public boolean equals(Object other) { return getName().equals(((Employee) other).getName()); }

Clone Method Usage

Severity: Medium

Summary

Every implementation of clone() should invoke super.clone() and every clone() method should be final.

Description

This audit rule looks for implementations of the method clone() that do not invoke the inherited clone() method. It also looks for clone() methods that are not declared final.

Example

The following declaration of the clone method would be flagged as being a violation, both because of the lack of an invocation of the inherited clone method and because it is not declared 'final'.

public Object clone() { return new Employee(getName()); }

Command Execution

Severity: Medium

Summary

External commands should not be executed because not all platforms have the same syntax for executing them.

Description

The method Runtime.exec() should not be used to execute commands because the format of command execution is platform dependent.

Example

The following invocation of the exec() method would be flagged as a violation:

Runtime.exec("c:binmyApp.exe", new String[0]);

Convert Class to Interface

Severity: Medium

Summary

Some classes could be converted to interfaces.

Description

This audit rule finds classes containing no methods or only abstract methods, and no fields or only static final fields. Classes such as these could be converted to an equivalent interface providing increased implementation flexibility.

Example

The following class declaration would be flagged as a violation:

public abstract class RunnableWithException { public abstract void run() throws Exception; }

Dangling Else

Severity: Medium

Summary

Use blocks to prevent dangling else clauses.

Description

This audit rule finds places in the code where else clauses are not preceded by a block because these can lead to dangling else errors.

Example

if (a > 0) if (a > 100) b = a - 100; else b = -a;

Declare As Interface

Severity: Medium

Summary

Variables of certain types should be declared using an interface.

Description

This audit rule finds declarations of fields and variables whose type should have been declared to be an interface but was declared to be a class that implements the interface instead. The list of interfaces that are checked can be configured.

Example

If the type java.util.List is on the list of interfaces, the following would be flaged as a violation because the declared type of the field should have been "List":

private ArrayList myList;

Declared Exceptions

Severity: Medium

Summary

Some exceptions should not be declared for methods or constructors.

Description

This audit rule finds methods and constructors that declare as a thrown exception an exception class that is disallowed. The list initially includes exception classes that are either too general (such as Throwable or Exception), or that are unchecked (Error, RuntimeException, and all subclasses of either).

Example

If the rule is configured to disallow the declaration of unchecked exceptions, then the following method would be flagged as a violation:

public void initialize() throws Error { ... }

Default Not Last in Switch

Severity: Medium

Summary

The default case should be the last case in a switch statement.

Description

This audit rule finds switch statements in which the default case is not the last case. Making the default case always be last improves the readability of the code by making it easier to locate the default behavior.

Example

The following case statement would be flagged as a violation because the default case is not the last case:

switch (registrationType) { case 0: \ audit ... default: case 1: \ for credit ... case 2: \ pass/fail ... }

Define Initial Capacity

Severity: Medium

Summary

Define an initial capacity for 'ArrayList','HashMap', 'HashSet', 'Hashtable', 'Vector', 'WeakHashMap' or 'StringBuffer' instances.

Description

This audit rule requires an initial capacity to be specified when creating 'ArrayList','HashMap', 'HashSet', 'Hashtable', 'Vector', 'WeakHashMap' or 'StringBuffer'. Array capacity expansion involves allocating a larger array and copying the contents of the old array to a new one. The old array object eventually gets reclaimed by the garbage collector. Array expansion is an expensive operation which should be avoided where possible. If you are able to approximate the expected size, you should use this value instead of the default.

Example

The following instance creation would be flagged as a violation because the expected size of the collection is not specified:

new ArrayList();

Disallow Native Methods

Severity: Medium

Summary

Native methods should be avoided because they are often platform dependent.

Description

Native methods should be avoided because they are often platform dependent.

Example

The following method declaraction would be flagged as a violation because it is implemented as a native method:

public int native getUID();

Disallow Notify Usage

Severity: Medium

Summary

The notify() method should not be used.

Description

The method notifyAll() should be used rather than notify() because it will generally lead to a better scheduling of waiting threads.

Example

The following invocation of the notify() method would be flagged as a violation:

synchronize (monitor) { monitor.notify(); }

Disallow Sleep Inside While

Severity: Medium

Summary

The sleep() method should not be used within a while loop.

Description

This audit rule looks for invocations of the sleep() method that occur inside of a while loop. Such occurances usually indicate that the code implements a busy-wait loop, which is inefficient. Instead, the code should use wait() and notify() to block the thread until it is possible for execution to proceed.

Example

The following invocation of the sleep() method would be flagged as a violation:

while (eventQueue.isEmpty()) { Thread.sleep(); }

Disallow ThreadGroup Usage

Severity: Medium

Summary

The class ThreadGroup should not be used.

Description

The class ThreadGroup should not be used in multi-threaded applications because its implementation is not thread safe.

Example

The following instance creation would be flagged as a violation because it is creating an instance of the class java.lang.ThreadGroup:

new ThreadGroup("Background Threads")

Disallow Use of AWT Peer Classes

Severity: High

Summary

AWT peer classes should not be referenced because they are platform dependent.

Description

The AWT peer classes provide a platform-specific implementation of the AWT widgets. Referencing any of these classes directly will result in platform dependent code.

Example

The following reference to the class sun.awt.windows.WButtonPeer would be flagged as a violation because it is specific to the Windows platform:

if (peer instanceof sun.awt.windows.WButtonPeer)

Disallow Use of Deprecated Thread Methods

Severity: Medium

Summary

Don't use deprecated methods when writing multi-threaded code.

Description

The methods Thread.resume(), Thread.stop(), Thread.suspend() and Runtime.runFinalizersOnExit() have been deprecated and should not be used because they are inherently unsafe.

Example

The following use of the suspend() method would be flagged as a violation:

processingThread.suspend();

Disallow Yield Usage

Severity: Medium

Summary

The method Thread.yield() should not be used.

Description

The method Thread.yield() should not be used because its behavior is not consistent across all platforms.

Example

The following invocation of the yield() method would be flagged as a violation:

backgroundTask.yield();

Duplicate Property Name

Severity: High

Summary

Properties should only be declared once.

Description

This audit rule checks to ensure that there is never more than one property declaration with the same name in the same file. Declaring multiple properties with the same name is usually a mistake because only the last such property will be visible to the code.

Example

applicationName = CoolApp applicationName = Ice Machine Controller

Duplicate Property Value

Severity: Low

Summary

Properties should only be declared once.

Description

This audit rule checks to ensure that there is never more than one property declaration with the same value in the same file. Declaring multiple properties with the same value can needlessly increase the amount of effort required to translate the property values into another locale.

Example

importBottonLabel = Import... importMenuLabel = Import...

Efficient Expression

Severity: Medium

Summary

Some expressions are more efficient than others.

Description

This rule finds expressions that can be replaced with other equivalent and more efficient expressions.

Example

The expression

(new Integer("1234")).intValue()

should be replaced by

Integer.parseInt("1234")

because the latter expression does not create an intermediate Integer object and thus is more efficient.

Empty Catch Clause

Severity: Medium

Summary

Catch clauses should not be empty.

Description

This rule finds places where an exception is caught and nothing is done. It can be configured to allow the existence of a comment to substitute for actual Java code.

Example

try { ... } catch (Exception exception) { }

Empty Finally Clause

Severity: Medium

Summary

Finally clauses should never be empty.

Description

This audit rule finds finally clauses whose block is empty.

Example

try { ... } finally { }

Empty Statement

Severity: High

Summary

Empty statements should never be used.

Description

This audit rule finds places where an empty statement occurs within a control structure. (An empty statement is a semi-colon appearing alone in a place where a statement is allowed). The existence of an empty statement usually indicates a problem, such as a piece of code that was unintentionally removed or a semicolon added in the wrong place.

Example

if (hasBeenAuthenticated); grantSpecialAccess();

Empty Synchronized Statement

Severity: High

Summary

Synchronized statements should never be empty.

Description

This audit rule finds empty synchronized statements.

Example

synchronized (monitor) { }

Enforce Singleton Property with Private Constructor

Severity: Medium

Summary

Flag classes that appear to follow the Singleton pattern but have a non-private constructor.

Description

Ensure that a class defined as a singleton follows specific rules that disallow multiple instances to be created. Singleton classes should have a single, private constructor and static access to the instance.

Entry Point Method

Severity: Medium

Summary

The main() method should be defined as "public static void main(java.lang.String[])".

Description

This audit rule finds main() methods that are not defined as "public static void main(java.lang.String[])". The main() method should only be used as the entry point for a class.

Example

The following method would be flagged as a violation because it is not declared to be a static method:

public void main(String[] args) { ... }

Environment Variable Access

Severity: High

Summary

Environment variables should not be accessed because not all platforms have support for environment variables.

Description

The method System.getenv() should not be used to access environment variables because not all platforms have support for environment variables. Properties should be used instead.

Example

The following invocation of the getenv() method would be flagged as a violation:

System.getenv("PATH");

Equality Test with Boolean Literal

Severity: Medium

Summary

Boolean literals should never be used in equality tests.

Description

This audit rule finds equality tests (using either == or !=) in which either or both of the operands are a Boolean literal (either true or false).

Example

if (todayIsTuesday() == true) { ... }

Expression Evaluation

Severity: Medium

Summary

Expression evaluation.

Description

This set of audit rules checks the value of expressions for certain conditions. It detects constant and zero values, divide-by-zero, and others.

Example

The following expression would be flagged as a violation because it always produces the same value:

int secondsPerDay = 24 * 60 * 60;

The following expression would be flagged as a violation because it will always cause a divide by zero exception:

return 23 / 0;

Extra Semicolon

Severity: Low

Summary

Extra semicolons clutter the code and serve no useful purpose.

Description

This audit rule finds places where a semicolon occurs but is not needed. While not strictly an error, such semicolons clutter the code and serve no useful purpose.

Example

while (index < count) { index = index + 1;; };

Finalize Method Definition

Severity: Medium

Summary

Finalize methods should not have parameters or a non-void return type.

Description

The only way to declare a finalize method is

public void finalize() [throws Throwable]

You can create other finalize methods that take parameters, but they will not be called automatically by the system, and may confuse anyone reading the code. You should reserve the name finalize for the real finalize method. This audit rule finds finalize() methods that have parameters or do not have a void return type.

Example

The following method declaration would be flagged as a violation because the method returns an integer:

public int finalize() { ... }

Float Comparison

Severity: Medium

Summary

Floating-point values should not be compared using equals (==) or not equals (!=).

Description

This audit rule finds places where two floating-point values are compared using either the equals (==) or not equals (!=) operators. The problem is that floating-point values are not exact, and floating-point operations sometimes introduce rounding errors. This sometimes results in getting the wrong result from equality-based comparisons.

Example

Given two floating point variables:

double oneThird = 1.0 / 3.0; double anotherThird = (2.0 / 3.0) - oneThird;

The following expression would be flagged as a violation:

if (oneThird == anotherThird)

Hiding Inherited Fields

Severity: Medium

Summary

Inherited fields should not be hidden.

Description

This audit rule finds fields that hide inherited fields. That is, it finds fields that have the same name as a field from a superclass.

Example

Given a class declaration like the following:

public class Person { private String name; ... }

The field declaration in the following class declaration would be flagged as a violation:

public class Employee extends Person { private String name; ... }

Hiding Inherited Static Methods

Severity: Medium

Summary

Inherited static methods should not be hidden.

Description

This audit rule finds methods that hide inherited static methods. That is, it finds methods that have the same name and compatible argument types as a static method from a superclass. The problem with defining methods like this is that it is too easy to miss the fact that the methods are static and that the subclasses method therefore does not override the method from the superclass.

Example

Given a class declaration like the following:

public class Person { public static Person newNamed(String name) { ... } ... }

The method declaration in the following class declaration would be flagged as a violation:

public class Employee extends Person { public static Person newNamed(String name) { ... } ... }

Instance Field Security

Severity: Medium

Summary

Refrain from using non-final public instance fields.

Description

To the extent possible, refrain from using non-final public instance fields. Instead, let the interface to your instance field be through accessor methods. In this way it is possible to add centralized security checks, if required.

Example

The following field declaration would be flagged as a violation because it is both public and non-final:

public int width;

Instance Field Visibility

Severity: Medium

Summary

Instance fields should have an appropriate visibility.

Description

This audit rule checks the visibility of all non-static fields to ensure that it is one of the allowed visibilities.

Example

If the rule were configured to only allow private instance fields, then the following field declaration would be flagged as a violation because it is declared as being public:

public int x;

Invoke super.finalize() from finalize()

Severity: Medium

Summary

Every implementation of finalize() should invoke super.finalize().

Description

This audit rule looks for implementations of the method finalize() that do not invoke the inherited finalize() method.

Example

The following definition of the method finalize() would be flagged because it does not invoke the inherited implementation of finalize():

public void finalize() { if (fileReader != null) { fileReader.close(); fileReader = null; } }

Large Number of Parameters

Severity: Medium

Summary

Methods should not have too many parameters.

Description

This audit rule finds methods that have more than the specified number of parameters. Methods that exceed this number are likely to be too complex. Consider moving some of the values and behavior associated with them into a separate class.

Example

If the rule is configured to allow 4 parameters and a method with 12 parameters is found, that method will be flagged as a violation.

Large Number of Switch Statement Cases

Severity: Medium

Summary

Switch statements should not have more than 256 case clauses.

Description

This audit rule looks for switch statements that have more than 256 case clauses. Some processors have special support for switch statements and some JITs will take advantage of such instructions when there are few enough cases.

Example

If a switch statement with more than 256 case clauses is found, it will be flagged as a violation.

Loss of Precision in Cast

Severity: Medium

Summary

Casting to a lower precision type can cause loss of data.

Description

This audit rule checks for places where one numeric type is being cast to another type of lower precision than the first. Doing so can result in a loss of data, which is generally not desirable.

Example

Given a declaration of the form:

double oneThird = 1.0 / 3.0;

The following expression would be flagged as a violation:

(float) oneThird

Method Chain Length

Severity: Medium

Summary

Method invocations should not be chained into a long line.

Description

This audit rule looks for places where multiple method invocations are chained together into an overly long chain. There are two problems with long chains of method invocations. The most obvious is that they can make the code difficult to follow. An even more serious problem is that they often point out places where information has not been well encapsulated.

Example

Color roofColor = party.getWorkAddress().getStructure().getRoof().getColor();

Missing Block

Severity: Medium

Summary

A single statement should never be used where a block is allowed.

Description

This audit rule checks for statements that control the execution of another statement (do, for, if or while) to ensure that the statement being controlled is always a block.

Example

if (color == null) color = getDefaultColor();

Missing Default in Switch

Severity: Medium

Summary

Every switch statement should have a default clause.

Description

This audit rule checks for the existence of a default case within every switch statement.

Example

The following switch statement would be flagged as a violation because it does not contain a "default" case label:

switch (accountType) { case CHECKING_ACCOUNT: balance = ((CheckingAccount) account).getCheckingBalance(); case SAVINGS_ACCOUNT: balance = ((SavingsAccount) account).getSavingsBalance(); }

No Run Method

Severity: Medium

Summary

Subclasses of Thread should implement the run() method.

Description

Subclasses of Thread should implement the run() method so that they will have the behavior for which they were created.

Example

The following class will be flagged as a violation because it does not implement a run() method even though it subclasses java.lang.Thread:

public class SuperThread extends Thread { }

Non-blank Final Instance Field

Severity: Medium

Summary

Final instance fields should be blank.

Description

This audit rule finds instance fields that are marked as final and have a value assigned to them in the declaration. If the value of the field is the same for all instances, which it must be in this case, it should be a static field instead. If the value can be different in different instances, then either the field should not be final or the field should be assigned its value in a constructor.

Example

The following field declaration would be flagged as a violation:

private final int maxItemCount = 64;

Non-case Label in Switch

Severity: Medium

Summary

Switch statements should only contain case labels.

Description

This audit rule finds labels other that case labels that appear within a switch statement. Such labels are often the result of forgetting to type the keyword "case" rather than an intent to use a labeled statement. If it isn't the result of an accident, having a labeled statement in a switch statement makes the logic much harder to understand because it can easily be mistaken for a case label.

Example

The statement labeled "SAVINGS_ACCOUNT" would be flagged as a violation:

switch (accountType) { case CHECKING_ACCOUNT: balance = ((CheckingAccount) account).getCheckingBalance(); SAVINGS_ACCOUNT: balance = ((SavingsAccount) account).getSavingsBalance(); }

Non-private Constructor in Static Type

Severity: Medium

Summary

Constructors in classes containing only static members should be private.

Description

This audit rule finds non-private constructors in classes containing only static members. There is no value in creating an instance of a type that contains only static members. To prevent such instantiation, ensure that type has a single, no-argument, private constructor and no other constructors.

Example

The following class declaration would be flagged as a violation:

public class Utilities { public static int getSize(List list) { ... } }

Non-protected Constructor in Abstract Type

Severity: Medium

Summary

Constructors in abstract classes should be protected.

Description

This audit rule finds non-protected constructors in abstract classes. Constructors in an abstract class can only be called from an instantiating subclass. Marking all constructors protected will help indicate this.

Example

The constructor in the following class declaration would be flagged as a violation:

public abstract class Widget { public Widget() { ... } }

Non-terminated Case Clause

Severity: Medium

Summary

Case clauses should never fall through into the following case.

Description

This audit rule checks for the existence of either a break, continue, return, or throw statement at the end of each case clause in a switch statement. The lack of either of these statements means that control will fall through to the next case, which is usually not what is intended. It is possible to configure this rule to also accept a user-defined comment (such as "no break") as a signal that the developer knew what was happening.

Example

switch (accountType) { case CHECKING_ACCOUNT: balance = ((CheckingAccount) account).getCheckingBalance(); case SAVINGS_ACCOUNT: balance = ((SavingsAccount) account).getSavingsBalance(); }

Obey General Contract of Equals

Severity: Medium

Summary

Obey the general contract when overriding equals().

Description

The equals() method defined in Object is intended to be overridden by subclasses but each subclass must obey the general contract specified by the superclass. Classes should not use the name "equals" for methods that take any parameters other than a single Object. The body of the method should be coded defensively to accept any class of object as its argument.

Example

The style of equals() definition that this rule looks for is this:

public boolean equals(Object arg) { if (this == arg) return true; if (!(arg instanceof Foo)) return false; Foo fooArg = (Foo) arg; ... }

"Foo" is the name of a type, which is either the class that declares this equals() method or an interface that is implemented by that class.

Overloaded Methods

Severity: Medium

Summary

Overloading method names can cause confusion and errors.

Description

This audit rule finds methods that are overloaded. Overloaded methods are methods that have the same name and the same number of parameters, but do not have the same types of parameters. Such methods can cause confusion and errors because it is not always obvious which method will be selected at run time.

Example

public void process(Person person) public void process(Employee employee)

Override both equals() and hashCode()

Severity: Medium

Summary

Classes should override both equals() and hashCode() if they override either.

Description

This audit rule finds classes in which either the equals() or hashCode() method has been overridden, but not both.

Example

The following class declaration will be flagged as a violation because it overrides the method equals() but does not override the method hashCode():

public class Employee { private String name;

...

public boolean equals(Object object) { return object instanceof Employee && getName().equals(((Employee) object).getName()); } }

Overriding a Non-abstract Method with an Abstract Method

Severity: Medium

Summary

An abstract method should not override a non-abstract method.

Description

This audit rule finds abstract methods that override a non-abstract method. Such a case usually represents a violation of the inherited contract.

Example

Given the following class:

public class Widget { public int getPartCount() { return 0; } }

The method getPartCount() would be flagged as a violation in the following class:

public abstract class CompositeWidget extends Widget { public abstract int getPartCount(); }

Overriding a Synchronized Method with a Non-synchronized Method

Severity: Medium

Summary

A non-synchronized method should not override a synchronized method.

Description

This audit rule finds non-synchronized methods that override a synchronized method. Such a case usually indicates thread-unsafe code.

Example

public class Widget { public synchronized int getPartCount() { return 0; } }

The method getPartCount() would be flagged as a violation in the following class:

public class CompositeWidget extends Widget { public int getPartCount() { return children.size(); } }

Overriding Private Method

Severity: Medium

Summary

Methods cannot override a private method.

Description

This audit rule looks for methods that look like they were intended to override a method from a superclass but fail because the inherited method is defined to be a private method.

Example

Given the following class:

public class TreeNode { private int getChildCount() { return children.size(); } }

The method getChildCount() would be flagged as a violation in the following class:

public abstract class LeafNode extends TreeNode { private int getChildCount() { return 0; } }

Parenthesize Condition in Conditional Operator

Severity: Low

Summary

The condition in a conditional operator should be parenthesized if it contains a binary operator.

Description

This audit rule looks for uses of the conditional operator in which the condition contains a binary operator but has not been parenthesized.

Example

The following expression would be flagged as a violation because the condition is not parenthesized:

childCount = children == null ? 0 : children.size();

Platform Specific Line Separator

Severity: High

Summary

Line separators should not be hard-coded because they are platform dependent.

Description

Line separators should not be hard-coded because they are platform dependent.

Example

The following use of the escape sequence " " would be flagged as a violation because not all platforms use it as a line separator:

text = title + "

" + message;

Preferred Expression

Severity: Low

Summary

Some expressions are preferred over other equivalent expressions.

Description

This audit rule searches for expressions that can be replaced with other equivalent and more preferred expressions. Specifically Colors can be replaced with Color constants and Booleans with Boolean constants.

Example

The expression

new Color(0, 0, 0)

can be replaced by

Color.black

and the expression

new Boolean(true)

can be replaced by

Boolean.TRUE

Questionable Assignment

Severity: Medium

Summary

Questionable assignments may lead to semantic errors.

Description

This audit rule checks for assignments to for loop variables within the loop body or assignments to method parameters within the body of the method. While these may sometimes prove useful they often have unintended side effects. Be sure you really mean to make these assignments!

Example

The assignment to "index" in the following method would be flagged as a violation because it is a method parameter:

public int lastIndexOf(Object[] array, Object value, int index) { index = array.size() - 1; while (index >= 0) { ... } }

Redundant Assignment

Severity: High

Summary

Redundant assignments should never be used.

Description

This audit rule checks for the assignment of a variable to itself. This often indicates a missing qualifier, such as "this." for one or the other of the identifiers.

Example

public void setName(String name) { name = name; }

Restricted Superclasses

Severity: Medium

Summary

Some classes should never be directly subclassed even though they cannot be marked as final.

Description

This audit rule finds classes that directly subclass any of a list of classes that should never be directly subclassed. It is typically the case that there are subclasses of these classes that can be subclassed.

Example

If the rule is configured to disallow direct subclasses of java.lang.Throwable, the following class declaration would be flagged as a violation:

public class QuestionableResult extends Throwable { ... }

Rethrown Exceptions

Severity: Medium

Summary

Some exceptions should be rethrown.

Description

This audit rule finds catch clauses that do not rethrow the original exception. The list initially includes Error and ThreadDeath. For example, if ThreadDeath is not rethrown, then the thread will not terminate.

Example

If the rule has been configured to require that instances of the class java.lang.ThreadDeath must be rethrown, the following catch clause would be flagged as a violation:

try { ... } catch (ThreadDeath exception) { resource.release(); }

Return in Finally

Severity: Medium

Summary

Finally blocks should not contain a return statement.

Description

This audit rule finds places where a return statement is contained in a finally block.

Example

The following return statement would be flagged as a violation:

try { ... } finally { return 0; } return array.length;

Reusable Immutables

Severity: Medium

Summary

Objects that cannot be modified at run-time should be created as static constants.

Description

This audit rule finds the creation of some kinds of immutable objects. An immutable object is an object whose state cannot be modified at run-time. Such objects should be created as constants (static final fields) so that in order to reduce the amount of garbage that must be collected.

Example

new Integer(5); new int[0];

Serializable Usage

Severity: Medium

Summary

Serializable classes should be define properly.

Description

This audit rule finds classes that are defined as Serializable (that implement the interface java.io.Serializable) that have specific problems or that do not need to be defined as Serializable.

Example

The following class would be flagged as a violation because it does not define any instance fields:

public class Utilities implements Serializable { public static double computeInterest(double amount, double interestRate, double payment) { ... } }

Static Field Security

Severity: Medium

Summary

Refrain from using non-final public static fields.

Description

To the extent possible, refrain from using non-final public static fields because there is no way to check whether the code that changes such fields has appropriate permissions.

Example

The following declaration would be flagged as a violation because it it both public and non-final:

public static int minutesPerHour = 60;

String Comparison

Severity: Medium

Summary

Strings should not be compared using equals (==) or not equals (!=).

Description

Strings should always be compared using one of the comparison methods defined for strings. This audit rule looks for comparisons using either the equals (==) or not equals (!=) operators.

Example

String currentName, proposedName;

... if (proposedName != currentName) { ... }

String Concatenation in Loop

Severity: Medium

Summary

Strings should not be concatenated within a loop.

Description

The code to concatenate two strings is not very efficient because it creates a StringBuffer for each concatenation. When placed in a loop, this can result in the creation and collection of large numbers of temporary objects. You can create the StringBuffer before entering the loop, and append to it within the loop, thus reducing the overhead.

Example

String[] path; String result = ""; for (int i = 0; i < path.length; i++) { result = result + "." + path[i]; }

String Created from Literal

Severity: Medium

Summary

Strings should not be created from a String literal.

Description

This audit rule finds places in the code where a String literal is used to initialize a newly created String. Doing so is almost never necessary and usually only serves to waste both time and space.

Example

The following expression would be flagged as a violation:

new String("Pause");

Synchronized Method

Severity: Medium

Summary

Methods should never be marked as synchronized.

Description

This audit rule reports the use of the synchronized modifier with methods. It is too easy to miss the existence of the synchronized modifier, so following this rule leads to more readable code.

Example

public synchronized String getName() { ... }

Temporary Object Creation

Severity: Low

Summary

Instances of numeric classes should not be created solely for the purpose of converting a numeric value to a string.

Description

This audit rule checks for the creation of numeric classes where the only purpose for the object is to invoke the toString() method on it. All of the numeric classes implement a static toString() method that can do the same thing, but without the cost of creating and collecting an extra object.

Example

The following expression would be flagged as a violation:

(new Integer(age)).toString()

Throw in Finally

Severity: Medium

Summary

Finally blocks should not contain a throw statement.

Description

This audit rule finds places where a throw statement is contained in a finally block.

Example

The following throw statement would be flagged as a violation because it occurs within a finally block:

try { ... } finally { throw new Exception("This is never OK"); }

Thrown Exceptions

Severity: Medium

Summary

Some exceptions should not be thrown.

Description

This audit rule finds throw statements that throw an exception class that is disallowed. The list initially includes exception classes that are either too general (such as Throwable or Exception), or that are unchecked (Error, RuntimeException, and all subclasses of either).

Example

If the rule is configured to disallow throwing of instances of Throwable, then the following throw statement would be flagged as a violation:

throw new Throwable("Bet this won't get caught");

Type Depth

Severity: Medium

Summary

Types should not be deeply nested.

Description

This audit rule finds source in which type declarations are deeply nested. The maximum depth can be configured. Type level types have a depth of zero (0), so a maximum depth of 2 would mean, for example, that an inner class of a top-level class could have an anonymous inner class without being flagged, but a third level of nesting would be flagged.

Unnecessary "instanceof" Test

Severity: Medium

Summary

Unnecessary instanceof tests should be removed.

Description

This audit rule looks for unnecessary usages of "instanceof". An "instanceof" test against a superclass or superinterface of the static type of an object is unnecessary and should be removed.

Example

"this is a string" instanceof String;

Unnecessary Return Statement Parentheses

Severity: Low

Summary

The expression in a return statement should not be parenthesized.

Description

This audit rule looks for return statements where the expression that computes the value to be returned is enclosed in parentheses. They are unnecessary and typically make the code harder to read and maintain.

Example

The following return statement's expression would be flagged as a violation because the parentheses are not necessary:

return (x * x);

Unnecessary Type Cast

Severity: Medium

Summary

Unnecessary type casts should be removed.

Description

This audit rule checks for places where a value is being cast to another type and the type case is not necessary.

Example

int i = (int) 0; Object o = (Object) new String();

Use "for" Loops Instead of "while" Loops

Severity: Low

Summary

Disallows the use of "while" loops.

Description

This audit rule checks for the use of "while" loops rather than "for" loops. "for" loops allow loop-scoped variables to be declared during loop setup, minimizing the scope of loop-control variables to just the body of the loop. Since their scope ends after the loop, they cannot be referenced later accidentally.

Example

The following while loop would be flagged as a violation:

int index = 0; while (index < array.length) { ... index++; }

because it should be rewritten as:

for (int i = 0; i < array.length; i++) { ... }

Use charAt() Rather Than startsWith()

Severity: Medium

Summary

Use charAt() rather than startsWith() when the constant is a single character string.

Description

Use charAt(0) rather than startsWith("string constant") when the constant is a single character string. Using startsWith() with a one character argument works, but it makes several computations while preparing to compare its prefix with another string, which is unnecessary when you just want to compare one character against another.

Example

The following method invocation would be flagged as a violation:

string.startsWith("<")

because the condition could more efficiently be tested using:

string.charAt(0) == '<'

Use equals() Rather Than ==

Severity: Medium

Summary

Values should not be compared using equals (==) or not equals (!=).

Description

This audit rule finds places where two values are compared using either the equals (==) or not equals (!=) operators.

Example

The following expression would be flagged as a violation:

if (firstString == secondString) {

because it should be rewritten as:

if (firstString.equals(secondString)) {

Use of "instanceof" with "this"

Severity: Medium

Summary

The type of "this" should not be tested using "instanceof".

Description

This audit rule checks for places where the type of "this" is being tested using the "instanceof" operator. Code that depends on the type of an object should be distributed to the sublasses so that polymorphism will automatically choose the right code to execute.

Example

if (this instanceof SpecialSublass) ...

Variable Declared Within a Loop

Severity: Low

Summary

One should be careful when declaring variables inside of for, while, or do loops. This may lead to problems especially if the variable is initialized as well.

Description

This audit rule looks for variables that have been declared or initialized within a for, while, or do loop.

Declaring a variable within a loop breaks some suggested style rules.

Initializing a variable within a loop may indicate a problem with the program's logic. It could also lead to degraded performance.

Example

The following declaration of the variable "event" would be flagged as a violation:

while (hasMoreEvents()) { Event event = getNextEvent(); ... }

Variable Should Be Final

Severity: Medium

Summary

Variables that are assigned only once should be final. Variables marked as final communicate additional information to the reader about how the variable is supposed to be used.

Description

This audit rule finds private fields that have a value assigned in an initializer or in a constructor and no where else, and local variables that have a value assigned in their initializer and no where else. The variable should be marked as final indicating that the value of the variable does not change through out the variable's lifetime.

Variable Usage

Severity: Medium

Summary

Variables should never shadow variables with the same name that are defined in an outer scope.

Description

This audit rule checks for any declarations of variables that shadow a variable with the same name that is defined in an outer scope.

Example

In a class with a field declaration such as:

private int inventoryCount;

the following parameter would be flagged as a violation:

public void printInventory(int inventoryCount)

Wait Inside While

Severity: Medium

Summary

The wait() method should only be invoked within a while loop.

Description

This audit rule looks for invocations of the wait() method that occur outside of a while loop.

Example

The following invocation of the wait() method would be flagged as a violation:

public void waitForEvent() { synchronize (eventQueue) { eventQueue.wait(); ... } }

White Space Before Property Name

Severity: High

Summary

Property names should not be preceeded by white space.

Description

This audit rule looks for property names that are preceeded by white space. Property names that are preceeded by white space often indicate a missing line continuation character on the preceeding line.

Example

The property named "operation" below, which was likely intended to be part of the line before it, would be flagged as a violation:

messageText = You should have known better than to have tried this operation without first changing your preference settings.

Wrong Integer Type Suffix

Severity: Low

Summary

Long literals should use 'L' for a suffix.

Description

This audit rule looks for long-valued literals whose suffix is a lowercase 'l'. Although the language specification allows this, it is too easily confused with the number one (1), and hence should not be used.

Example

public static final long ONE = 1l;

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.