public final class PMDWarnings extends Object
SuppressWarnings annotation.| Modifier and Type | Field and Description |
|---|---|
static String |
ABSTRACT_CLASS_WITH_ABSTRACT_METHOD
The abstract class does not contain any abstract methods.
|
static String |
ABSTRACT_CLASS_WITHOUT_ANY_METHOD
If an abstract class does not provides any methods, it may be acting as a simple data container that is not meant
to be instantiated.
|
static String |
ABSTRACT_NAMING
Abstract classes should be named 'AbstractXXX'.
|
static String |
ACCESSOR_CLASS_GENERATION
Instantiation by way of private constructors from outside of the constructor's class often causes the generation
of an accessor.
|
static String |
ADD_EMPTY_STRING
The conversion of literals to strings by concatenating them with empty strings is inefficient.
|
static String |
APPEND_CHARACTER_WITH_CHAR
Avoid concatenating characters as strings in StringBuffer/StringBuilder.append methods.
|
static String |
ARRAY_IS_STORED_DIRECTLY
Constructors and methods receiving arrays should clone objects and store the copy.
|
static String |
ASSIGNMENT_IN_OPERAND
Avoid assignments in operands; this can make code more complicated and harder to read.
|
static String |
ASSIGNMENT_TO_NON_FINAL_STATIC
Identifies a possible unsafe usage of a static field.
|
static String |
AT_LEAST_ONE_CONSTRUCTOR
Each class should declare at least one constructor.
|
static String |
AVOID_ACCESSIBILITY_ALTERATION
Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface
PrivilegedAction, allows for the runtime alteration of variable, class, or method visibility, even if they are
private.
|
static String |
AVOID_ARRAY_LOOPS
Instead of manually copying data between two arrays, use the efficient System.arraycopy method instead.
|
static String |
AVOID_ASSERT_AS_IDENTIFIER
Use of the term 'assert' will conflict with newer versions of Java since it is a reserved word.
|
static String |
AVOID_BRANCHING_STATEMENT_AS_LAST_IN_LOOP
Using a branching statement as the last part of a loop may be a bug, and/or is confusing.
|
static String |
AVOID_CALLING_FINALIZE
The method Object.finalize() is called by the garbage collector on an object when garbage collection determines
that there are no more references to the object.
|
static String |
AVOID_CATCHING_GENERIC_EXCEPTION
Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block.
|
static String |
AVOID_CATCHING_NPE
Code should never throw NullPointerExceptions under normal circumstances.
|
static String |
AVOID_CATCHING_THROWABLE
Catching Throwable errors is not recommended since its scope is very broad.
|
static String |
AVOID_CONSTANTS_INTERFACE
An interface should be used only to characterize the external behaviour of an implementing class: using an
interface as a container of constants is a poor usage pattern and not recommended.
|
static String |
AVOID_DECIMAL_LITERALS_IN_BIG_DECIMAL_CONSTRUCTOR
One might assume that the result of "new BigDecimal(0.1)" is exactly equal to 0.1, but it is actually equal to
.1000000000000000055511151231257827021181583404541015625.
|
static String |
AVOID_DEEPLY_NESTED_IF_STATEMENTS
Avoid creating deeply nested if-then statements since they are harder to read and error-prone to maintain.
|
static String |
AVOID_DOLLAR_SIGNS
Avoid using dollar signs in variable/method/class/interface names.
|
static String |
AVOID_DUPLICATE_LITERALS
Code containing duplicate String literals can usually be improved by declaring the String as a constant field.
|
static String |
AVOID_ENUM_AS_IDENTIFIER
Use of the term 'enum' will conflict with newer versions of Java since it is a reserved word.
|
static String |
AVOID_FIELD_NAME_MATCHING_METHOD_NAME
It can be confusing to have a field name with the same name as a method.
|
static String |
AVOID_FIELD_NAME_MATCHING_TYPE_NAME
It is somewhat confusing to have a field name matching the declaring class name.
|
static String |
AVOID_FINAL_LOCAL_VARIABLE
Avoid using final local variables, turn them into fields.
|
static String |
AVOID_INSTANCEOF_CHECKS_IN_CATCH_CLAUSE
Each caught exception type should be handled in its own catch clause.
|
static String |
AVOID_INSTANTIATING_OBJECTS_IN_LOOPS
New objects created within loops should be checked to see if they can created outside them and reused.
|
static String |
AVOID_LITERALS_IN_IF_CONDITION
Avoid using hard-coded literals in conditional statements.
|
static String |
AVOID_LOSING_EXCEPTION_INFORMATION
Statements in a catch block that invoke accessors on the exception without using the information only add to code
size.
|
static String |
AVOID_MULTIPLE_UNARY_OPERATORS
The use of multiple unary operators may be problematic, and/or confusing.
|
static String |
AVOID_PREFIXING_METHOD_PARAMETERS
Prefixing parameters by 'in' or 'out' pollutes the name of the parameters and reduces code readability.
|
static String |
AVOID_PRINT_STACK_TRACE
Avoid printStackTrace(); use a logger call instead.
|
static String |
AVOID_PROTECTED_FIELD_IN_FINAL_CLASS
Do not use protected fields in final classes since they cannot be subclassed.
|
static String |
AVOID_REASSIGNING_PARAMETERS
Reassigning values to incoming parameters is not recommended.
|
static String |
AVOID_RETHROWING_EXCEPTION
Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity.
|
static String |
AVOID_STRING_BUFFER_FIELD
StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks if held within
objects with long lifetimes.
|
static String |
AVOID_SYNCHRONIZED_AT_METHOD_LEVEL
Method-level synchronization can cause problems when new code is added to the method.
|
static String |
AVOID_THREAD_GROUP
Avoid using java.lang.ThreadGroup; although it is intended to be used in a threaded environment it contains
methods that are not thread-safe.
|
static String |
AVOID_THROWING_NEW_INSTANCE_OF_SAME_EXCEPTION
Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same type only add to
code size and runtime complexity.
|
static String |
AVOID_THROWING_NULL_POINTER_EXCEPTION
Avoid throwing NullPointerExceptions.
|
static String |
AVOID_THROWING_RAW_EXCEPTION_TYPES
Avoid throwing certain exception types.
|
static String |
AVOID_USING_HARD_CODED_IP
Application with hard-coded IP addresses can become impossible to deploy in some cases.
|
static String |
AVOID_USING_NATIVE_CODE
Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portability and increases
the maintenance burden.
|
static String |
AVOID_USING_OCTAL_VALUES
Integer literals should not start with zero since this denotes that the rest of literal will be interpreted as an
octal value.
|
static String |
AVOID_USING_SHORT_TYPE
Java uses the 'short' type to reduce memory usage, not to optimize calculation.
|
static String |
AVOID_USING_VOLATILE
Use of the keyword 'volatile' is generally used to fine tune a Java application, and therefore, requires a good
expertise of the Java Memory Model.
|
static String |
BAD_COMPARISON
Avoid equality comparisons with Double.NaN.
|
static String |
BEAN_MEMBERS_SHOULD_SERIALIZE
If a class is a bean, or is referenced by a bean directly or indirectly it needs to be serializable.
|
static String |
BIG_INTEGER_INSTANTIATION
Don't create instances of already existing BigInteger (BigInteger.ZERO, BigInteger.ONE) and for Java 1.5 onwards,
BigInteger.TEN and BigDecimal (BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN)
|
static String |
BOOLEAN_GET_METHOD_NAME
Methods that return boolean results should be named as predicate statements to denote this.
|
static String |
BOOLEAN_INSTANTIATION
Avoid instantiating Boolean objects; you can reference Boolean.TRUE, Boolean.FALSE, or call Boolean.valueOf()
instead.
|
static String |
BOOLEAN_INVERSION
Use bitwise inversion to invert boolean values - it's the fastest way to do this.
|
static String |
BROKEN_NULL_CHECK
The null check is broken since it will throw a NullPointerException itself.
|
static String |
BYTE_INSTANTIATION
Calling new Byte() causes memory allocation that can be avoided by the static Byte.valueOf().
|
static String |
CALL_SUPER_IN_CONSTRUCTOR
It is a good practice to call super() in a constructor.
|
static String |
CHECK_RESULT_SET
Always check the return values of navigation methods (next, previous, first, last) of a ResultSet.
|
static String |
CHECK_SKIP_RESULT
The skip() method may skip a smaller number of bytes than requested.
|
static String |
CLASS_CAST_EXCEPTION_WITH_TO_ARRAY
When deriving an array of a specific class from your Collection, one should provide an array of the same class as
the parameter of the toArray() method.
|
static String |
CLASS_NAMING_CONVENTIONS
Class names should always begin with an upper case character.
|
static String |
CLASS_WITH_ONLY_PRIVATE_CONSTRUCTOR_SHOULD_BE_FINAL
A class with only private constructors should be final, unless the private constructor is invoked by a inner
class.
|
static String |
CLONE_METHOD_MUST_IMPLEMENT_CLONEABLE
The method clone() should only be implemented if the class implements the Cloneable interface with the exception
of a final method that only throws CloneNotSupportedException.
|
static String |
CLONE_THROWS_CLONE_NOT_SUPPORTED_EXCEPTION
The method clone() should throw a CloneNotSupportedException.
|
static String |
CLOSE_RESOURCE
Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use.
|
static String |
COLLAPSIBLE_IF_STATEMENTS
Sometimes two consecutive 'if' statements can be consolidated by separating their conditions with a boolean
short-circuit operator.
|
static String |
COMMENT_CONTENT
A rule for the politically correct...
|
static String |
COMMENT_REQUIRED
Denotes whether comments are required (or unwanted) for specific language elements.
|
static String |
COMMENT_SIZE
Determines whether the dimensions of non-header comments found are within the specified limits.
|
static String |
COMPARE_OBJECTS_WITH_EQUALS
Use equals() to compare object references; avoid comparing them with ==.
|
static String |
CONFUSING_TERNARY
Avoid negation within an "if" expression with an "else" clause.
|
static String |
CONSECUTIVE_LITERAL_APPENDS
Consecutively calling StringBuffer/StringBuilder.append with String literals
|
static String |
CONSTRUCTOR_CALLS_OVERRIDABLE_METHOD
Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed
object and can be difficult to debug.
|
static String |
COUPLING_BETWEEN_OBJECTS
This rule counts the number of unique attributes, local variables, and return types within an object.
|
static String |
CYCLOMATIC_COMPLEXITY
Complexity directly affects maintenance costs is determined by the number of decision points in a method plus one
for the method entry.
|
static String |
DATAFLOW_ANOMALY_ANALYSIS
The dataflow analysis tracks local definitions, undefinitions and references to variables on different paths on
the data flow.
|
static String |
DEFAULT_LABEL_NOT_LAST_IN_SWITCH_STATEMENT
By convention, the default label should be the last label in a switch statement.
|
static String |
DEFAULT_PACKAGE
Use explicit scoping instead of the default package private level.
|
static String |
DO_NOT_CALL_GARBAGE_COLLECTION_EXPLICITLY
Calls to System.gc(), Runtime.getRuntime().gc(), and System.runFinalization() are not advised.
|
static String |
DO_NOT_CALL_SYSTEM_EXIT
Web applications should not call System.exit(), since only the web container or the application server should
stop the JVM.
|
static String |
DO_NOT_EXTEND_JAVA_LANG_ERROR
Errors are system exceptions.
|
static String |
DO_NOT_THROW_EXCEPTION_IN_FINALLY
Throwing exceptions within a 'finally' block is confusing since they may mask other exceptions or code defects.
|
static String |
DO_NOT_USE_THREADS
The J2EE specification explicitly forbids the use of threads.
|
static String |
DONT_CALL_THREAD_RUN
Explicitly calling Thread.run() method will execute in the caller's thread of control.
|
static String |
DONT_IMPORT_JAVA_LANG
Avoid importing anything from the package 'java.lang'.
|
static String |
DONT_IMPORT_SUN
Avoid importing anything from the 'sun.*' packages.
|
static String |
DONT_USE_FLOAT_TYPE_FOR_LOOP_INDICES
Don't use floating point for loop indices.
|
static String |
DOUBLE_CHECKED_LOCKING
Partially created objects can be returned by the Double Checked Locking pattern when used in Java.
|
static String |
DUPLICATE_IMPORTS
Duplicate or overlapping import statements should be avoided.
|
static String |
EMPTY_CATCH_BLOCK
Empty Catch Block finds instances where an exception is caught, but nothing is done.
|
static String |
EMPTY_FINALLY_BLOCK
Empty finally blocks serve no purpose and should be removed.
|
static String |
EMPTY_FINANLIZER
Empty finalize methods serve no purpose and should be removed.
|
static String |
EMPTY_IF_STATEMENT
Empty If Statement finds instances where a condition is checked but nothing is done about it.
|
static String |
EMPTY_INITIALIZER
Empty initializers serve no purpose and should be removed.
|
static String |
EMPTY_METHOD_IN_ABSTRACT_CLASS_SHOULD_BE_ABSTRACT
Empty methods in an abstract class should be tagged as abstract.
|
static String |
EMPTY_STATEMENT_BLOCK
Empty block statements serve no purpose and should be removed.
|
static String |
EMPTY_STATEMENT_NOT_IN_LOOP
An empty statement (or a semicolon by itself) that is not used as the sole body of a 'for' or 'while' loop is
probably a bug.
|
static String |
EMPTY_STATIC_INITIALIZER
An empty static initializer serve no purpose and should be removed.
|
static String |
EMPTY_SWITCH_STATEMENTS
Empty switch statements serve no purpose and should be removed.
|
static String |
EMPTY_SYNCHRONIZED_BLOCK
Empty synchronized blocks serve no purpose and should be removed.
|
static String |
EMPTY_TRY_BLOCK
Avoid empty try blocks - what's the point?
|
static String |
EMPTY_WHILE_STATEMENT
Empty While Statement finds all instances where a while statement does nothing.
|
static String |
EQUALS_NULL
Tests for null should not use the equals() method.
|
static String |
EXCEPTION_AS_FLOW_CONTROL
Using Exceptions as form of flow control is not recommended as they obscure true exceptions when debugging.
|
static String |
EXCESSIVE_CLASS_LENGTH
Excessive class file lengths are usually indications that the class may be burdened with excessive
responsibilities that could be provided by external classes or functions.
|
static String |
EXCESSIVE_IMPORTS
A high number of imports can indicate a high degree of coupling within an object.
|
static String |
EXCESSIVE_METHOD_LENGTH
When methods are excessively long this usually indicates that the method is doing more than its name/signature
might suggest.
|
static String |
EXCESSIVE_PARAMETER_LIST
Methods with numerous parameters are a challenge to maintain, especially if most of them share the same datatype.
|
static String |
EXCESSIVE_PUBLIC_COUNT
Classes with large numbers of public methods and attributes require disproportionate testing efforts since
combinational side effects grow rapidly and increase risk.
|
static String |
EXTENDS_OBJECT
No need to explicitly extend Object.
|
static String |
FIELD_DECLARATIONS_SHOULD_BE_AT_START_OF_CLASS
Fields should be declared at the top of the class, before any method declarations, constructors, initializers or
inner classes.
|
static String |
FINAL_FIELD_COULD_BE_STATIC
If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each
object at runtime.
|
static String |
FINALIZE_DOES_NOT_CALL_SUPER_FINALIZE
If the finalize() is implemented, its last action should be to call super.finalize.
|
static String |
FINALIZE_ONLY_CALLS_SUPER_FINALIZE
If the finalize() is implemented, it should do something besides just calling super.finalize().
|
static String |
FINALIZE_OVERLOADED
Methods named finalize() should not have parameters.
|
static String |
FINALIZE_SHOULD_BE_PROTECTED
When overriding the finalize(), the new method should be set as protected.
|
static String |
FOR_LOOP_SHOULD_BE_WHILE_LOOP
Some for loops can be simplified to while loops, this makes them more concise.
|
static String |
FOR_LOOPS_MUST_USE_BRACES
Avoid using 'for' statements without using curly braces.
|
static String |
GENERICS_NAMING
Names for references to generic values should be limited to a single uppercase letter.
|
static String |
GOD_CLASS
The God Class rule detects the God Class design flaw using metrics.
|
static String |
GUARD_DEBUG_LOGGING
When log messages are composed by concatenating strings, the whole section should be guarded by a
isDebugEnabled() check to avoid performance and memory issues.
|
static String |
IDEMPOTENT_OPERATIONS
Avoid idempotent operations - they have no effect.
|
static String |
IF_ELSE_STATEMENTS_MUST_USE_BRACES
Avoid using if..else statements without using surrounding braces.
|
static String |
IF_STMTS_MUST_USE_BRACES
Avoid using if statements without using braces to surround the code block.
|
static String |
IMMUTABLE_FIELD
Identifies private fields whose values never change once they are initialized either in the declaration of the
field or by a constructor.
|
static String |
IMPORT_FROM_SAME_PACKAGE
There is no need to import a type that lives in the same package.
|
static String |
INEFFICIENT_EMPTY_STRING_CHECK
String.trim().length() is an inefficient way to check if a String is really empty, as it creates a new String
object just to check its size.
|
static String |
INEFFICIENT_STRING_BUFFERING
Avoid concatenating non-literals in a StringBuffer constructor or append() since intermediate buffers will need
to be be created and destroyed by the JVM.
|
static String |
INSTANTIATION_TO_GET_CLASS
Avoid instantiating an object just to call getClass() on it; use the .class public member instead.
|
static String |
INSUFFICIENT_STRING_BUFFER_DECLARATION
Failing to pre-size a StringBuffer or StringBuilder properly could cause it to re-size many times during runtime.
|
static String |
INTEGER_INSTANTIATION
Calling new Integer() causes memory allocation that can be avoided by the static Integer.valueOf().
|
static String |
JUMBLED_INCREMENTER
Avoid jumbled loop incrementers - its usually a mistake, and is confusing even if intentional.
|
static String |
JUNIT_4_SUITES_SHOULD_USE_SUITE_ANNOTATION
In JUnit 3, test suites are indicated by the suite() method.
|
static String |
JUNIT_4_TEST_SHOULD_USE_AFTER_ANNOTATION
In JUnit 3, the tearDown method was used to clean up all data entities required in running tests.
|
static String |
JUNIT_4_TEST_SHOULD_USE_BEFORE_ANNOTATION
In JUnit 3, the setUp method was used to set up all data entities required in running tests.
|
static String |
JUNIT_4_TEST_SHOULD_USE_TEST_ANNOTATION
In JUnit 3, the framework executed all methods which started with the word test as a unit test.
|
static String |
JUNIT_ASSERTIONS_SHOULD_INCLUDE_MESSAGE
JUnit assertions should include an informative message - i.e., use the three-argument version of assertEquals(),
not the two-argument version.
|
static String |
JUNIT_SPELLING
Some JUnit framework methods are easy to misspell.
|
static String |
JUNIT_STATIC_SUITE
The suite() method in a JUnit test needs to be both public and static.
|
static String |
JUNIT_TEST_CONTAINS_TOO_MANY_ASSERTS
JUnit tests should not contain too many asserts.
|
static String |
JUNIT_TESTS_SHOULD_INCLUDE_ASSERT
JUnit tests should include at least one assertion.
|
static String |
JUNIT_USE_EXPECTED
In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions.
|
static String |
LAW_OF_DEMETER
The Law of Demeter is a simple rule, that says "only talk to friends".
|
static String |
LOCAL_HOME_NAMING_CONVENTION
The Local Home interface of a Session EJB should be suffixed by 'LocalHome'.
|
static String |
LOCAL_INTERFACE_SESSION_NAMING_CONVENTION
The Local Interface of a Session EJB should be suffixed by 'Local'.
|
static String |
LOCAL_VARIABLE_COULD_BE_FINAL
A local variable assigned only once can be declared final.
|
static String |
LOGGER_IS_NOT_STATIC_FINAL
In most cases, the Logger reference can be declared as static and final.
|
static String |
LOGIC_INVERSION
Use opposite operator instead of negating the whole expression with a logic complement operator.
|
static String |
LONG_INSTANTIATION
Calling new Long() causes memory allocation that can be avoided by the static Long.valueOf().
|
static String |
LONG_VARIABLE
Fields, formal arguments, or local variable names that are too long can make the code difficult to follow.
|
static String |
LOOSE_COUPLING
The use of implementation types as object references limits your ability to use alternate implementations in the
future as requirements change.
|
static String |
LOOSE_PACKAGE_COUPLING
Avoid using classes from the configured package hierarchy outside of the package hierarchy, except when using one
of the configured allowed classes.
|
static String |
MDB_AND_SESSION_BEAN_NAMING_CONVENTION
The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by 'Bean'.
|
static String |
METHOD_ARGUMENT_COULD_BE_FINAL
A method argument that is never re-assigned within the method can be declared final.
|
static String |
METHOD_NAMING_CONVENTIONS
Method names should always begin with a lower case character, and should not contain underscores.
|
static String |
METHOD_RETURNS_INTERNAL_ARRAY
Exposing internal arrays to the caller violates object encapsulation since elements can be removed or replaced
outside of the object that owns it.
|
static String |
METHOD_WITH_SAME_NAME_AS_ENCLOSING_CLASS
Non-constructor methods should not have the same name as the enclosing class.
|
static String |
MISLEADING_VARIABLE_NAME
Detects when a non-field has a name starting with 'm_'.
|
static String |
MISPLACED_NULL_CHECK
The null check here is misplaced.
|
static String |
MISSING_BREAK_IN_SWITCH
Switch statements without break or return statements for each case option may indicate problematic behaviour.
|
static String |
MISSING_SERIAL_VERSION_UID
Serializable classes should provide a serialVersionUID field.
|
static String |
MISSING_STATIC_METHOD_IN_NON_INSTANTIATABLE_CLASS
A class that has private constructors and does not have any static methods or fields cannot be used.
|
static String |
MORE_THAN_ONE_LOGGER
Normally only one logger is used in each class.
|
static String |
NCSS_CONSTRUCTOR_COUNT
This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for
a given constructor.
|
static String |
NCSS_METHOD_COUNT
This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for
a given method.
|
static String |
NCSS_TYPE_COUNT
This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for
a given type.
|
static String |
NO_PACKAGE
Detects when a class or interface does not have a package definition.
|
static String |
NON_CASE_LABEL_IN_SWITCH_STATEMENT
A non-case label (e.g.
|
static String |
NON_STATIC_INITIALIZER
A non-static initializer block will be called any time a constructor is invoked (just prior to invoking the
constructor).
|
static String |
NON_THREAD_SAFE_SINGLETON
Non-thread safe singletons can result in bad state changes.
|
static String |
NPATH_COMPLEXITY
The NPath complexity of a method is the number of acyclic execution paths through that method.
|
static String |
NULL_ASSIGNMENT
Assigning a "null" to a variable (outside of its declaration) is usually bad form.
|
static String |
ONE_DECLARATION_PER_LINE
Java allows the use of several variables declaration of the same type on one line.
|
static String |
ONLY_ONE_RETURN
A method should have only one exit point, and that should be the last statement in the method.
|
static String |
OPTIMIZABLE_TO_ARRAY_CALL
Calls to a collection's toArray() method should specify target arrays sized to match the size of the collection.
|
static String |
OVERRIDE_BOTH_EQUALS_AND_HASHCODE
Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither.
|
static String |
PACKAGE_CASE
Detects when a package definition contains uppercase characters.
|
static String |
PMD
Suppresses all PMD warnings
|
static String |
POSITION_LITERALS_FIRST_IN_COMPARISONS
Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided,
they will just return false.
|
static String |
PREMATURE_DECLARATION
Checks for variables that are defined before they might be used.
|
static String |
PRESERVE_STACK_TRACE
Throwing a new exception from a catch block without passing the original exception into the new exception will
cause the original stack trace to be lost making it difficult to debug effectively.
|
static String |
PROPER_CLONE_IMPLEMENTATION
Object clone() should be implemented with super.clone().
|
static String |
PROPER_LOGGER
A logger should normally be defined private static final and be associated with the correct class.
|
static String |
REDUNDANT_FIELD_INITIALIZER
Java will initialize fields with known default values so any explicit initialization of those same defaults is
redundant and results in a larger class file (approximately three additional bytecode instructions per field).
|
static String |
REMOTE_INTERFACE_NAMING_CONVENTION
Remote Interface of a Session EJB should not have a suffix.
|
static String |
REMOTE_SESSION_INTERFACE_NAMING_CONVENTION
A Remote Home interface type of a Session EJB should be suffixed by 'Home'.
|
static String |
REPLACE_ENUMERATION_WITH_ITERATOR
Consider replacing Enumeration usages with the newer java.util.Iterator
|
static String |
REPLACE_HASHTABLE_WITH_MAP
Consider replacing Hashtable usage with the newer java.util.Map if thread safety is not required.
|
static String |
REPLACE_VECTOR_WITH_LIST
Consider replacing Vector usages with the newer java.util.ArrayList if expensive thread-safe operations are not
required.
|
static String |
RETURN_EMPTY_ARRAY_RATHER_THAN_NULL
For any method that returns an array, it is a better to return an empty array rather than a null reference.
|
static String |
RETURN_FROM_FINALLY_BLOCK
Avoid returning from a finally block, this can discard exceptions.
|
static String |
SHORT_CLASS_NAME
Classnames with fewer than five characters are not recommended.
|
static String |
SHORT_INSTANTIATION
Calling new Short() causes memory allocation that can be avoided by the static Short.valueOf().
|
static String |
SHORT_METHOD_NAME
Method names that are very short are not helpful to the reader.
|
static String |
SHORT_VARIABLE
Fields, local variables, or parameter names that are very short are not helpful to the reader.
|
static String |
SIGNATURE_DECLARE_THROWS_EXCEPTION
Methods that declare the generic Exception as a possible throwable are not very helpful since their failure modes
are unclear.
|
static String |
SIMPLE_DATE_FORMAT_NEEDS_LOCALE
Be sure to specify a Locale when creating SimpleDateFormat instances to ensure that locale-appropriate formatting
is used.
|
static String |
SIMPLIFY_BOOLEAN_ASSERTION
Avoid negation in an assertTrue or assertFalse test.
|
static String |
SIMPLIFY_BOOLEAN_EXPRESSIONS
Avoid unnecessary comparisons in boolean expressions, they serve no purpose and impacts readability.
|
static String |
SIMPLIFY_BOOLEAN_RETURNS
Avoid unnecessary if-then-else statements when returning a boolean.
|
static String |
SIMPLIFY_CONDITIONAL
No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.
|
static String |
SIMPLIFY_STARTS_WITH
Since it passes in a literal of length 1, calls to (string).startsWith can be rewritten using (string).charAt(0)
at the expense of some readability.
|
static String |
SINGULAR_FIELD
Fields whose scopes are limited to just single methods do not rely on the containing object to provide them to
other methods.
|
static String |
STATIC_EJB_FIELD_SHOULD_BE_FINAL
According to the J2EE specification, an EJB should not have any static fields with write access.
|
static String |
STRING_BUFFER_INSTANTIATION_WITH_CHAR
Individual character values provided as initialization arguments will be converted into integers.
|
static String |
STRING_INSTANTIATION
Avoid instantiating String objects; this is usually unnecessary since they are immutable and can be safely
shared.
|
static String |
STRING_TO_STRING
Avoid calling toString() on objects already known to be string instances; this is unnecessary.
|
static String |
SUSPICIOUS_CONSTANT_FIELD_NAME
Field names using all uppercase characters - Sun's Java naming conventions indicating constants - should be
declared as final.
|
static String |
SUSPICIOUS_EQUALS_METHOD_NAME
The method name and parameter number are suspiciously close to equals(Object), which can denote an intention to
override the equals(Object) method.
|
static String |
SUSPICIOUS_HASHCODE_METHOD_NAME
The method name and return type are suspiciously close to hashCode(), which may denote an intention to override
the hashCode() method.
|
static String |
SUSPICIOUS_OCTAL_ESCAPE
A suspicious octal escape sequence was found inside a String literal.
|
static String |
SWITCH_DENSITY
A high ratio of statements to labels in a switch statement implies that the switch statement is overloaded.
|
static String |
SWITCH_STATEMENTS_SHOULD_HAVE_DEFAULT
All switch statements should include a default option to catch any unspecified values.
|
static String |
SYSTEM_PRINTLN
References to System.(out|err).print are usually intended for debugging purposes and can remain in the codebase
even in production code.
|
static String |
TEST_CLASS_WITHOUT_TEST_CASES
Test classes end with the suffix Test.
|
static String |
TOO_FEW_BRANCHES_FOR_A_SWITCH_STATEMENT
Switch statements are indended to be used to support complex branching behaviour.
|
static String |
TOO_MANY_FIELDS
Classes that have too many fields can become unwieldy and could be redesigned to have fewer fields, possibly
through grouping related fields in new objects.
|
static String |
TOO_MANY_METHODS
A class with too many methods is probably a good suspect for refactoring, in order to reduce its complexity and
find a way to have more fine grained objects.
|
static String |
TOO_MANY_STATIC_IMPORTS
If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its
namespace with all the static members you import.
|
static String |
UNCOMMENTED_EMPTY_CONSTRUCTOR
Uncommented Empty Constructor finds instances where a constructor does not contain statements, but there is no
comment.
|
static String |
UNCOMMENTED_EMPTY_METHOD
Uncommented Empty Method finds instances where a method does not contain statements, but there is no comment.
|
static String |
UNCONDITIONAL_IF_STATEMENT
Do not use "if" statements whose conditionals are always true or always false.
|
static String |
UNNECESSARY_BOOLEAN_ASSERTION
A JUnit test assertion with a boolean literal is unnecessary since it always will evaluate to the same thing.
|
static String |
UNNECESSARY_CASE_CHANGE
Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()
|
static String |
UNNECESSARY_CONSTRUCTOR
This rule detects when a constructor is not necessary; i.e., when there is only one constructor, its public, has
an empty body, and takes no arguments.
|
static String |
UNNECESSARY_CONVERSION_TEMPORARY
Avoid the use temporary objects when converting primitives to Strings.
|
static String |
UNNECESSARY_FINAL_MODIFIER
When a class has the final modifier, all the methods are automatically final and do not need to be tagged as
such.
|
static String |
UNNECESSARY_FULLY_QUALIFIED_NAME
Import statements allow the use of non-fully qualified names.
|
static String |
UNNECESSARY_LOCAL_BEFORE_RETURN
Avoid the creation of unnecessary local variables.
|
static String |
UNNECESSARY_PARENTHESES
Sometimes expressions are wrapped in unnecessary parentheses, making them look like function calls.
|
static String |
UNNECESSARY_RETURN
Avoid the use of unnecessary return statements.
|
static String |
UNNECESSARY_WRAPPER_OBJECT_CREATION
Most wrapper classes provide static conversion methods that avoid the need to create intermediate objects just to
create the primitive forms.
|
static String |
UNSYCHRONIZED_STATIC_DATE_FORMATTER
SimpleDateFormat instances are not synchronized.
|
static String |
UNUSED_FORMAL_PARAMETER
Avoid passing parameters to methods or constructors without actually referencing them in the method body.
|
static String |
UNUSED_IMPORTS
Avoid the use of unused import statements to prevent unwanted dependencies.
|
static String |
UNUSED_LOCAL_VARIABLE
Detects when a local variable is declared and/or assigned, but not used.
|
static String |
UNUSED_MODIFIER
Fields in interfaces are automatically public static final, and methods are public abstract.
|
static String |
UNUSED_NULL_CHECK_IN_EQUALS
After checking an object reference for null, you should invoke equals() on that object rather than passing it to
another object's equals() method.
|
static String |
UNUSED_PRIVATE_FIELD
Detects when a private field is declared and/or assigned a value, but not used.
|
static String |
UNUSED_PRIVATE_METHOD
Unused Private Method detects when a private method is declared but is unused.
|
static String |
USE_ARRAY_LIST_INSTEAD_OF_VECTOR
ArrayList is a much better Collection implementation than Vector if thread-safe operation is not required.
|
static String |
USE_ARRAYS_AS_LIST
The java.util.Arrays class has a "asList" method that should be used when you want to create a new List from an
array of objects.
|
static String |
USE_ASSERT_EQUALS_INSTEAD_OF_ASSERT_TRUE
This rule detects JUnit assertions in object equality.
|
static String |
USE_ASSERT_NULL_INSTEAD_OF_ASSERT_TRUE
This rule detects JUnit assertions in object references equality.
|
static String |
USE_ASSERT_SAME_INSTEAD_OF_ASSERT_TRUE
This rule detects JUnit assertions in object references equality.
|
static String |
USE_ASSERT_TRUE_INSTEAD_OF_ASSERT_EQUALS
When asserting a value is the same as a boolean literal, use assertTrue/assertFalse, instead of assertEquals.
|
static String |
USE_COLLECTION_IS_EMPTY
The isEmpty() method on java.util.Collection is provided to determine if a collection has any elements.
|
static String |
USE_CONCURRENT_HASH_MAP
Since Java5 brought a new implementation of the Map designed for multi-threaded access, you can perform efficient
map reads without blocking other threads.
|
static String |
USE_CORRECT_EXCEPTION_LOGGING
To make sure the full stacktrace is printed out, use the logging statement with two arguments: a String and a
Throwable.
|
static String |
USE_EQUALS_TO_COMPARE_STRINGS
Using '==' or '!=' to compare strings only works if intern version is used on both sides.
|
static String |
USE_INDEX_OF_CHAR
Use String.indexOf(char) when checking for the index of a single character; it executes faster.
|
static String |
USE_LOCALE_WITH_CASE_CONVERSIONS
When doing String.toLowerCase()/toUpperCase() conversions, use Locales to avoids problems with languages that
have unusual conventions, i.e.
|
static String |
USE_NOTIFY_ALL_INSTEAD_OF_NOTIFY
Thread.notify() awakens a thread monitoring the object.
|
static String |
USE_OBJECT_FOR_CLEARER_API
When you write a public method, you should be thinking in terms of an API.
|
static String |
USE_PROPER_CLASS_LOADER
In J2EE, the getClassLoader() method might not work as expected.
|
static String |
USE_SINGLETON
For classes that only have static methods, consider making them Singletons.
|
static String |
USE_STRING_BUFFER_FOR_STRING_APPENDS
The use of the '+=' operator for appending strings causes the JVM to create and use an internal StringBuffer.
|
static String |
USE_STRING_BUFFER_LENGTH
Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toString().equals("")
or StringBuffer.toString().length() == ...
|
static String |
USE_VARARGS
Java 5 introduced the varargs parameter declaration for methods and constructors.
|
static String |
USELESS_OPERATION_ON_IMMUTABLE
An operation on an Immutable object (String, BigDecimal or BigInteger) won't change the object itself since the
result of the operation is a new object.
|
static String |
USELESS_OVERRIDING_METHOD
The overriding method merely calls the same method defined in a superclass.
|
static String |
USELESS_PARANTHESES
Useless parentheses should be removed.
|
static String |
USELESS_STRING_VALUE_OF
No need to call String.valueOf to append to a string; just use the valueOf() argument directly.
|
static String |
VARIABLE_NAMING_CONVENTIONS
A variable naming conventions rule - customize this to your liking.
|
static String |
WHILE_LOOPS_MUST_USE_BRACES
Avoid using 'while' statements without using braces to surround the code block.
|
public static final String PMD
public static final String JUMBLED_INCREMENTER
public class JumbledIncrementerRule {
public void foo() {
for (int i = 0; i < 10; i++) { // only references 'i'
for (int k = 0; k < 20; i++) { // references both 'i' and 'k'
System.out.println("Hello");
}
}
}
}
public static final String FOR_LOOP_SHOULD_BE_WHILE_LOOP
public class Foo {
void bar() {
// No Init or Update part, may as well be: while (true)
for (; true;) {
// do stuff..
}
}
}
public static final String OVERRIDE_BOTH_EQUALS_AND_HASHCODE
public class Bar { // poor, missing a hashcode() method
public boolean equals(Object o) {
// do some comparison
}
}
public class Baz { // poor, missing an equals() method
public int hashCode() {
// return some hash value
}
}
public class Foo { // perfect, both methods provided
public boolean equals(Object other) {
// do some comparison
}
public int hashCode() {
// return some hash value
}
}
public static final String DOUBLE_CHECKED_LOCKING
public class Foo {
Object baz;
Object bar() {
if (baz == null) { // baz may be non-null yet not fully created
synchronized (this) {
if (baz == null) {
baz = new Object();
}
}
}
return baz;
}
}
public static final String RETURN_FROM_FINALLY_BLOCK
public class Bar {
public String foo() {
try {
throw new Exception("My Exception");
} catch (Exception e) {
throw e;
} finally {
return "A. O. K."; // return not recommended here
}
}
}
public static final String UNCONDITIONAL_IF_STATEMENT
public class Foo {
public void close() {
if (true) { // fixed conditional, not recommended
// ...
}
}
}
public static final String BOOLEAN_INSTANTIATION
Boolean buz = Boolean.valueOf(false); // ...., just reference Boolean.FALSE
Boolean bar = new Boolean("true"); // unnecessary creation, just reference Boolean.TRUE
public static final String COLLAPSIBLE_IF_STATEMENTS
void bar() {
if (x) { // original implementation
if (y) {
// do stuff
}
}
}
void bar() {
if (x && y) { // optimized implementation
// do stuff
}
}
public static final String CLASS_CAST_EXCEPTION_WITH_TO_ARRAY
Collection c = new ArrayList(); Integer obj = new Integer(1); c.add(obj); // this would trigger the rule (and throw a ClassCastException if executed) Integer[] a = (Integer[]) c.toArray(); // this is fine and will not trigger the rule Integer[] b = (Integer[]) c.toArray(new Integer[c.size()]);
public static final String AVOID_DECIMAL_LITERALS_IN_BIG_DECIMAL_CONSTRUCTOR
BigDecimal bd = new BigDecimal(1.123); // loss of precision, this would trigger the rule
BigDecimal bd = new BigDecimal("1.123");// preferred approach
BigDecimal bd = new BigDecimal(12); // preferred approach, ok for integer values
public static final String MISPLACED_NULL_CHECK
NullPointerException will be thrown. Either
the check is useless (the variable will never be "null") or it is incorrect.
public class Foo {
void bar() {
if (a.equals(baz) && a != null) {
}
}
}
public class Foo {
void bar() {
if (a.equals(baz) || a == null) {
}
}
}
public static final String AVOID_THREAD_GROUP
public class Bar {
void buz() {
ThreadGroup tg = new ThreadGroup("My threadgroup");
tg = new ThreadGroup(tg, "my thread group");
tg = Thread.currentThread().getThreadGroup();
tg = System.getSecurityManager().getThreadGroup();
}
}
public static final String BROKEN_NULL_CHECK
public String bar(String string) {
// should be &&
if (string != null || !string.equals(""))
return string;
// should be ||
if (string == null && string.equals(""))
return string;
}
public static final String BIG_INTEGER_INSTANTIATION
BigInteger bi = new BigInteger(1); // reference BigInteger.ONE instead
BigInteger bi2 = new BigInteger("0"); // reference BigInteger.ZERO instead
BigInteger bi3 = new BigInteger(0.0); // reference BigInteger.ZERO instead
BigInteger bi4;
bi4 = new BigInteger(0); // reference BigInteger.ZERO instead
public static final String AVOID_USING_OCTAL_VALUES
int i = 012; // set i with 10 not 12
int j = 010; // set j with 8 not 10
k = i * j; // set k with 80 not 120
public static final String AVOID_USING_HARD_CODED_IP
public class Foo {
private String ip = "127.0.0.1"; // not recommended
}
public static final String CHECK_RESULT_SET
Statement stat = conn.createStatement();
ResultSet rst = stat.executeQuery("SELECT name FROM person");
rst.next(); // what if it returns false? bad form
String firstName = rst.getString(1);
Statement stat = conn.createStatement();
ResultSet rst = stat.executeQuery("SELECT name FROM person");
if (rst.next()) { // result is properly examined and used
String firstName = rst.getString(1);
} else {
// handle missing data
}
public static final String AVOID_MULTIPLE_UNARY_OPERATORS
// These are typo bugs, or at best needlessly complex and confusing:
int i = - -1;
int j = + - +1;
int z = ~~2;
boolean b = !!true;
boolean c = !!!true;
// These are better:
int i = 1;
int j = -1;
int z = 2;
boolean b = true;
boolean c = false;
// And these just make your brain hurt:
int i = ~-2;
int j = -~7;
public static final String EXTENDS_OBJECT
public class Foo extends Object { // not required
}
public static final String CHECK_SKIP_RESULT
public class Foo {
private FileInputStream _s = new FileInputStream("file");
public void skip(int n) throws IOException {
_s.skip(n); // You are not sure that exactly n bytes are skipped
}
public void skipExactly(int n) throws IOException {
while (n != 0) {
long skipped = _s.skip(n);
if (skipped == 0)
throw new EOFException();
n -= skipped;
}
}
public static final String AVOID_BRANCHING_STATEMENT_AS_LAST_IN_LOOP
// unusual use of branching statement in a loop
for (int i = 0; i < 10; i++) {
if (i * i <= 25) {
continue;
}
break;
}
// this makes more sense...
for (int i = 0; i < 10; i++) {
if (i * i > 25) {
break;
}
}
public static final String DONT_CALL_THREAD_RUN
Thread t = new Thread();
t.run(); // use t.start() instead
new Thread().run(); // same violation
public static final String DONT_USE_FLOAT_TYPE_FOR_LOOP_INDICES
public class Count {
public static void main(String[] args) {
final int START = 2000000000;
int count = 0;
for (float f = START; f < START + 50; f++)
count++;
// Prints 0 because (float) START == (float) (START + 50).
System.out.println(count);
// The termination test misbehaves due to floating point granularity.
}
}
public static final String IF_STMTS_MUST_USE_BRACES
if (foo) // not recommended
x++;
if (foo) { // preferred approach
x++;
}
public static final String WHILE_LOOPS_MUST_USE_BRACES
while (true)
// not recommended
x++;
while (true) { // preferred approach
x++;
}
public static final String IF_ELSE_STATEMENTS_MUST_USE_BRACES
// this is OK
if (foo)
x++;
// but this is not
if (foo)
x = x + 1;
else
x = x - 1;
public static final String FOR_LOOPS_MUST_USE_BRACES
for (int i = 0; i < 42; i++)
foo();
public static final String PROPER_CLONE_IMPLEMENTATION
class Foo {
public Object clone() {
return new Foo(); // This is bad
}
}
public static final String CLONE_THROWS_CLONE_NOT_SUPPORTED_EXCEPTION
public class MyClass implements Cloneable {
public Object clone() { // will cause an error
MyClass clone = (MyClass) super.clone();
return clone;
}
}
public static final String CLONE_METHOD_MUST_IMPLEMENT_CLONEABLE
public class MyClass {
public Object clone() throws CloneNotSupportedException {
return foo;
}
}
public static final String NPATH_COMPLEXITY
void bar() { // this is something more complex than it needs to be,
if (y) { // it should be broken down into smaller methods or functions
for (j = 0; j < m; j++) {
if (j > r) {
doSomething();
while (f < 5 ) {
anotherThing();
f -= 27;
}
} else {
tryThis();
}
}
}
if ( r - n > 45) {
while (doMagic()) {
findRabbits();
}
}
try {
doSomethingDangerous();
} catch (Exception ex) {
makeAmends();
} finally {
dontDoItAgain();
}
}
}
public static final String EXCESSIVE_METHOD_LENGTH
public void doSomething() {
System.out.println("Hello world!");
System.out.println("Hello world!");
// 98 copies omitted for brevity.
}
public static final String EXCESSIVE_PARAMETER_LIST
public void addPerson( // too many arguments liable to be mixed up
int birthYear, int birthMonth, int birthDate, int height, int weight, int ssn) {
. . . .
}
public void addPerson( // preferred approach
Date birthdate, BodyMeasurements measurements, int ssn) {
. . . .
}
public static final String EXCESSIVE_CLASS_LENGTH
public class Foo {
public void bar1() {
// 1000 lines of code
}
public void bar2() {
// 1000 lines of code
}
public void bar3() {
// 1000 lines of code
}
public void barN() {
// 1000 lines of code
}
}
public static final String CYCLOMATIC_COMPLEXITY
public class Foo { // This has a Cyclomatic Complexity = 12
1 public void example() {
2 if (a == b) {
3 if (a1 == b1) {
fiddle();
4 } else if a2 == b2) {
fiddle();
} else {
fiddle();
}
5 } else if (c == d) {
6 while (c == d) {
fiddle();
}
7 } else if (e == f) {
8 for (int n = 0; n < h; n++) {
fiddle();
}
} else{
switch (z) {
9 case 1:
fiddle();
break;
10 case 2:
fiddle();
break;
11 case 3:
fiddle();
break;
12 default:
fiddle();
break;
}
}
}
}
public static final String EXCESSIVE_PUBLIC_COUNT
public class Foo {
public String value;
public Bar something;
public Variable var;
// [... more more public attributes ...]
public void doWork() {
}
public void doMoreWork() {
}
public void doWorkAgain() {
}
// [... more more public methods ...]
}
public static final String TOO_MANY_FIELDS
public class Person { // too many separate fields
int birthYear;
int birthMonth;
int birthDate;
float height;
float weight;
}
public class Person { // this is more manageable
Date birthDate;
BodyMeasurements measurements;
}
public static final String NCSS_METHOD_COUNT
public class Foo extends Bar {
public int methd() {
super.methd();
// this method only has 1 NCSS lines
return 1;
}
}
public static final String NCSS_TYPE_COUNT
public class Foo extends Bar {
public Foo() {
// this class only has 6 NCSS lines
super();
super.foo();
}
}
public static final String NCSS_CONSTRUCTOR_COUNT
public class Foo extends Bar {
public Foo() {
super();
// this constructor only has 1 NCSS lines
super.foo();
}
}
public static final String TOO_MANY_METHODS
public static final String COMMENT_REQUIRED
public static final String COMMENT_SIZE
public static final String COMMENT_CONTENT
public static final String UNNECESSARY_CONSTRUCTOR
public class Foo {
public Foo() {
}
}
public static final String NULL_ASSIGNMENT
public void bar() {
Object x = null; // this is OK
x = new Object();
// big, complex piece of code here
x = null; // this is not required
// big, complex piece of code here
}
public static final String ONLY_ONE_RETURN
public class OneReturnOnly1 {
public void foo(int x) {
if (x > 0) {
return "hey"; // first exit
}
return "hi"; // second exit
}
}
public static final String ASSIGNMENT_IN_OPERAND
public void bar() {
int x = 2;
if ((x = getX()) == 3) {
System.out.println("3!");
}
}
public static final String AT_LEAST_ONE_CONSTRUCTOR
public class Foo {
// missing constructor
public void doSomething() { ... }
public void doOtherThing { ... }
}
public static final String DONT_IMPORT_SUN
import sun.misc.foo;
public static final String SUSPICIOUS_OCTAL_ESCAPE
public void foo() {
// interpreted as octal 12, followed by character '8'
System.out.println("suspicious: \128");
}
public static final String CALL_SUPER_IN_CONSTRUCTOR
public class Foo extends Bar {
public Foo() {
// call the constructor of Bar
super();
}
public Foo(int code) {
// do something with code
this();
// no problem with this
}
}
public static final String UNNECESSARY_PARENTHESES
public class Foo {
boolean bar() {
return (true);
}
}
public static final String DEFAULT_PACKAGE
public static final String BOOLEAN_INVERSION
boolean b = true; b = !b; // slow b ˆ= true; // fast
public static final String DATAFLOW_ANOMALY_ANALYSIS
public void foo() {
int buz = 5;
buz = 6; // redefinition of buz -> dd-anomaly
foo(buz);
buz = 2;
} // buz is undefined when leaving scope -> du-anomaly
public static final String AVOID_FINAL_LOCAL_VARIABLE
public class MyClass {
public void foo() {
final String finalLocalVariable;
}
}
public static final String AVOID_USING_SHORT_TYPE
public class UsingShort {
private short doNotUseShort = 0;
public UsingShort() {
short shouldNotBeUsed = 1;
doNotUseShort += shouldNotBeUsed;
}
}
public static final String AVOID_USING_VOLATILE
public class ThrDeux {
private volatile String var1; // not suggested
private String var2; // preferred
}
public static final String AVOID_USING_NATIVE_CODE
public class SomeJNIClass {
public SomeJNIClass() {
System.loadLibrary("nativelib");
}
static {
System.loadLibrary("nativelib");
}
public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException {
System.loadLibrary("nativelib");
}
}
public static final String AVOID_ACCESSIBILITY_ALTERATION
public class Violation {
public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException {
// Possible call to forbidden getDeclaredConstructors
Class[] arrayOfClass = new Class[1];
this.getClass().getDeclaredConstructors();
this.getClass().getDeclaredConstructor(arrayOfClass);
Class clazz = this.getClass();
clazz.getDeclaredConstructor(arrayOfClass);
clazz.getDeclaredConstructors();
// Possible call to forbidden setAccessible
clazz.getMethod("", arrayOfClass).setAccessible(false);
AccessibleObject.setAccessible(null, false);
Method.setAccessible(null, false);
Method[] methodsArray = clazz.getMethods();
int nbMethod;
for (nbMethod = 0; nbMethod < methodsArray.length; nbMethod++) {
methodsArray[nbMethod].setAccessible(false);
}
// Possible call to forbidden PrivilegedAction
PrivilegedAction priv = (PrivilegedAction) new Object();
priv.run();
}
}
public static final String DO_NOT_CALL_GARBAGE_COLLECTION_EXPLICITLY
public class GCCall {
public GCCall() {
// Explicit gc call !
System.gc();
}
public void doSomething() {
// Explicit gc call !
Runtime.getRuntime().gc();
}
public explicitGCcall() { // Explicit gc call ! System.gc(); }
public void doSomething() { // Explicit gc call ! Runtime.getRuntime().gc(); }
}
public static final String ONE_DECLARATION_PER_LINE
public class OneDeclaration {
String name, lastname; // combined declaration, a violation
}
public static final String AVOID_PREFIXING_METHOD_PARAMETERS
// Not really clear
public class Foo {
public void bar(int inLeftOperand, Result outRightOperand) {
outRightOperand.setValue(inLeftOperand * outRightOperand.getValue());
}
}
// Far more useful
public class Foo {
public void bar(final int leftOperand, final Result rightOperand) {
rightOperand.setValue(leftOperand * rightOperand.getValue());
}
}
public static final String AVOID_LITERALS_IN_IF_CONDITION
public class Literals {
private static final int TEN = 10;
public void downCastPrimitiveType() {
if (i == 10) { // magic number, buried in a method
doSomething();
}
if (i == TEN) { // preferred approach
doSomething();
}
}
}
public static final String USE_OBJECT_FOR_CLEARER_API
public class MyClass {
public void connect(String username, String pssd, String databaseName, String databaseAdress)
// Instead of those parameters object
// would ensure a cleaner API and permit
// to add extra data transparently (no code change):
// void connect(UserData data);
{
}
}
public static final String USE_CONCURRENT_HASH_MAP
public class ConcurrentApp {
public void getMyInstance() {
Map map1 = new HashMap(); // fine for single-threaded access
Map map2 = new ConcurrentHashMap(); // preferred for use with multiple threads
// the following case will be ignored by this rule
Map map3 = someModule.methodThatReturnMap(); // might be OK, if the returned map is already thread-safe
}
}
public static final String COUPLING_BETWEEN_OBJECTS
import com.Blah;
import org.Bar;
import org.Bardo;
public class Foo {
private Blah var1;
private Bar var2;
//followed by many imports of unique objects
void ObjectC doWork() {
Bardo var55;
ObjectA var44;
ObjectZ var93;
return something;
}
}
public static final String EXCESSIVE_IMPORTS
import blah.blah.Baz; // 18 others from the same package elided import blah.blah.Bif;
public static final String LOOSE_COUPLING
// sub-optimal approach
public HashSet getFoo() {
return new HashSet();
}
// preferred approach
public Set getFoo() {
return new HashSet();
}
public static final String LOOSE_PACKAGE_COUPLING
package some.package;
import some.other.package.subpackage.subsubpackage.DontUseThisClass;
public class Bar {
DontUseThisClass boo = new DontUseThisClass();
}
public static final String LAW_OF_DEMETER
public class Foo {
public void example(final Bar b) {
// this method call is ok, as b is a parameter of "example"
final C c = b.getC();
// this method call is a violation, as we are using c, which we got from B.
// We should ask b directly instead, e.g. "b.doItOnC();"
c.doIt();
// this is also a violation, just expressed differently as a method chain without temporary variables.
b.getC().doIt();
// a constructor call, not a method call.
final D d = new D();
// this method call is ok, because we have create the new instance of D locally.
d.doSomethingElse();
}
}
public static final String USE_SINGLETON
public class MaybeASingleton {
public static void foo() {
}
public static void bar() {
}
}
public static final String SIMPLIFY_BOOLEAN_RETURNS
public boolean isBarEqualTo(int x) {
if (bar == x) { // this bit of code...
return true;
} else {
return false;
}
}
public boolean isBarEqualTo(int x) {
return bar == x; // can be replaced with this
}
public static final String SIMPLIFY_BOOLEAN_EXPRESSIONS
public class Bar {
// can be simplified to
// bar = isFoo();
private boolean bar = (isFoo() == true);
public isFoo() {
return false;
}
}
public static final String SWITCH_STATEMENTS_SHOULD_HAVE_DEFAULT
public void bar() {
int x = 2;
switch (x) {
case 1:
int j = 6;
case 2:
int j = 8;
// missing default: here
}
}
public static final String AVOID_DEEPLY_NESTED_IF_STATEMENTS
public class Foo {
public void bar(int x, int y, int z) {
if (x > y) {
if (y > z) {
if (z == x) {
// !! too deep
}
}
}
}
}
public static final String AVOID_REASSIGNING_PARAMETERS
public class Foo {
private void foo(String bar) {
bar = "something else";
}
}
public static final String SWITCH_DENSITY
public class Foo {
public void bar(int x) {
switch (x) {
case 1: {
// lots of statements
break;
}
case 2: {
// lots of statements
break;
}
}
}
}
public static final String CONSTRUCTOR_CALLS_OVERRIDABLE_METHOD
public class SeniorClass {
public SeniorClass() {
toString(); // may throw NullPointerException if overridden
}
public String toString() {
return "IAmSeniorClass";
}
}
public class JuniorClass extends SeniorClass {
private String name;
public JuniorClass() {
super(); // Automatic call leads to NullPointerException
name = "JuniorClass";
}
public String toString() {
return name.toUpperCase();
}
}
public static final String ACCESSOR_CLASS_GENERATION
public class Outer {
void method() {
Inner ic = new Inner();// Causes generation of accessor class
}
public class Inner {
private Inner() {
}
}
}
public static final String FINAL_FIELD_COULD_BE_STATIC
public class Foo {
public final int BAR = 42; // this could be static and save some space
}
public static final String CLOSE_RESOURCE
public class Bar {
public void foo() {
Connection c = pool.getConnection();
try {
// do stuff
} catch (SQLException ex) {
// handle exception
} finally {
// oops, should close the connection using 'close'!
// c.close();
}
}
}
public static final String NON_STATIC_INITIALIZER
public class MyClass {
// this block gets run before any call to a constructor
{
System.out.println("I am about to construct myself");
}
}
public static final String DEFAULT_LABEL_NOT_LAST_IN_SWITCH_STATEMENT
public class Foo {
void bar(int a) {
switch (a) {
case 1: // do something
break;
default: // the default case should be last, by convention
break;
case 2:
break;
}
}
}
public static final String NON_CASE_LABEL_IN_SWITCH_STATEMENT
public class Foo {
void bar(int a) {
switch (a) {
case 1:
// do something
break;
mylabel:
// this is legal, but confusing!
break;
default:
break;
}
}
}
public static final String OPTIMIZABLE_TO_ARRAY_CALL
public void arrayCall() {
List foos = getFoos();
// inefficient, the array will be discarded
Foo[] fooArray = foos.toArray(new Foo[0]);
// much better; this one sizes the destination array,
// avoiding of a new one via reflection
Foo[] fooArray = foos.toArray(new Foo[foos.size()]);
}
public static final String BAD_COMPARISON
boolean x = (y == Double.NaN);
public static final String EQUALS_NULL
String x = "foo";
if (x.equals(null)) { // bad form
doSomething();
}
if (x == null) { // preferred
doSomething();
}
public static final String CONFUSING_TERNARY
boolean bar(int x, int y) {
return (x != y) ? diff : same;
}
public static final String INSTANTIATION_TO_GET_CLASS
public void instantiation() {
// replace this
Class c = new String().getClass();
// with this:
Class c = String.class;
}
public static final String IDEMPOTENT_OPERATIONS
public class Foo {
public void bar() {
int x = 2;
x = x;
}
}
public static final String SIMPLE_DATE_FORMAT_NEEDS_LOCALE
public class Foo {
// Should specify Locale.US (or whatever)
private SimpleDateFormat sdf = new SimpleDateFormat("pattern");
}
public static final String IMMUTABLE_FIELD
public class Foo {
private int x; // could be final
public Foo() {
x = 7;
}
public void foo() {
int a = x + 2;
}
}
public static final String USE_LOCALE_WITH_CASE_CONVERSIONS
class Foo {
// BAD
if (x.toLowerCase().equals("list"))...
// GOOD
String z = a.toLowerCase(Locale.EN);
}
public static final String AVOID_PROTECTED_FIELD_IN_FINAL_CLASS
public final class Bar {
private int x;
protected int y; // bar cannot be subclassed, so is y really private or package visible?
Bar() {
}
}
public static final String ASSIGNMENT_TO_NON_FINAL_STATIC
public class StaticField {
static int x;
public FinalFields(int y) {
x = y; // unsafe
}
}
public static final String MISSING_STATIC_METHOD_IN_NON_INSTANTIATABLE_CLASS
// This class is unusable, since it cannot be
// instantiated (private constructor),
// and no static method can be called.
public class Foo {
private Foo() {
}
void foo() {
}
}
public static final String AVOID_SYNCHRONIZED_AT_METHOD_LEVEL
public class Foo {
// Try to avoid this:
synchronized void foo() {
}
// Prefer this:
void bar() {
synchronized (this) {
}
}
// Try to avoid this for static methods:
static synchronized void fooStatic() {
}
// Prefer this:
static void barStatic() {
synchronized (Foo.class) {
}
}
}
public static final String MISSING_BREAK_IN_SWITCH
public void bar(int status) {
switch (status) {
case CANCELLED:
doCancelled();
// break; hm, should this be commented out?
case NEW:
doNew();
// is this really a fall-through?
case REMOVED:
doRemoved();
// what happens if you add another case after this one?
case OTHER: // empty case - this is interpreted as an intentional fall-through
case ERROR:
doErrorHandling();
break;
}
}
public static final String USE_NOTIFY_ALL_INSTEAD_OF_NOTIFY
void bar() {
x.notify();
// If many threads are monitoring x, only one (and you won't know which) will be notified.
// use instead:
x.notifyAll();
}
public static final String AVOID_INSTANCEOF_CHECKS_IN_CATCH_CLAUSE
try { // Avoid this
// do something
} catch (Exception ee) {
if (ee instanceof IOException) {
cleanup();
}
}
try { // Prefer this:
// do something
} catch (IOException ee) {
cleanup();
}
public static final String ABSTRACT_CLASS_WITH_ABSTRACT_METHOD
public abstract class Foo {
void int method1() { ... }
void int method2() { ... }
// consider using abstract methods or removing
// the abstract modifier and adding protected constructors
}
public static final String SIMPLIFY_CONDITIONAL
class Foo {
void bar(Object x) {
if (x != null && x instanceof Bar) {
// just drop the "x != null" check
}
}
}
public static final String COMPARE_OBJECTS_WITH_EQUALS
class Foo {
boolean bar(String a, String b) {
return a == b;
}
}
public static final String POSITION_LITERALS_FIRST_IN_COMPARISONS
class Foo {
boolean bar(String x) {
return x.equals("2"); // should be "2".equals(x)
}
}
public static final String UNNECESSARY_LOCAL_BEFORE_RETURN
public class Foo {
public int foo() {
int x = doSomething();
return x; // instead, just 'return doSomething();'
}
}
public static final String NON_THREAD_SAFE_SINGLETON
class Bar {
private static Foo foo = null;
// multiple simultaneous callers may see partially initialized objects
public static Foo getFoo() {
if (foo == null)
foo = new Foo();
return foo;
}
}
public static final String UNCOMMENTED_EMPTY_METHOD
public void doSomething() {
}
public static final String UNCOMMENTED_EMPTY_CONSTRUCTOR
public Foo() {
super();
}
public static final String AVOID_CONSTANTS_INTERFACE
public interface ConstantsInterface {
public static final int CONSTANT1 = 0;
public static final String CONSTANT2 = "1";
}
public static final String UNSYCHRONIZED_STATIC_DATE_FORMATTER
public class Foo {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void bar() {
sdf.format(); // poor, no thread-safety
}
synchronized void foo() {
sdf.format(); // preferred
}
}
public static final String PRESERVE_STACK_TRACE
public class Foo {
void good() {
try {
Integer.parseInt("a");
} catch (Exception e) {
throw new Exception(e); // first possibility to create exception chain
}
try {
Integer.parseInt("a");
} catch (Exception e) {
throw (IllegalStateException) new IllegalStateException().initCause(e); // second possibility to create
// exception chain.
}
}
void bad() {
try {
Integer.parseInt("a");
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
}
public static final String USE_COLLECTION_IS_EMPTY
public class Foo {
void good() {
List foo = getList();
if (foo.isEmpty()) {
// blah
}
}
void bad() {
List foo = getList();
if (foo.size() == 0) {
// blah
}
}
}
public static final String CLASS_WITH_ONLY_PRIVATE_CONSTRUCTOR_SHOULD_BE_FINAL
public class Foo { // Should be final
private Foo() {
}
}
public static final String EMPTY_METHOD_IN_ABSTRACT_CLASS_SHOULD_BE_ABSTRACT
public abstract class ShouldBeAbstract {
public Object couldBeAbstract() {
// Should be abstract method ?
return null;
}
public void couldBeAbstract() {
}
}
public static final String SINGULAR_FIELD
public class Foo {
private int x; // no reason to exist at the Foo instance level
public void foo(int y) {
x = y + 5;
return x;
}
}
public static final String RETURN_EMPTY_ARRAY_RATHER_THAN_NULL
public class Example {
// Not a good idea...
public int[] badBehavior() {
// ...
return null;
}
// Good behavior
public String[] bonnePratique() {
// ...
return new String[0];
}
}
public static final String ABSTRACT_CLASS_WITHOUT_ANY_METHOD
public class abstract Example {
String field;
int otherField;
}
public static final String TOO_FEW_BRANCHES_FOR_A_SWITCH_STATEMENT
public static final String LOGIC_INVERSION
public boolean bar(int a, int b) {
if (!(a == b)) // use !=
return false;
if (!(a < b)) // use >=
return false;
return true;
}
public static final String USE_VARARGS
public class Foo {
public void foo(String s, Object[] args) {
// Do something here...
}
public void bar(String s, Object... args) {
// Ahh, varargs tastes much better...
}
}
public static final String FIELD_DECLARATIONS_SHOULD_BE_AT_START_OF_CLASS
public class HelloWorldBean {
// Field declared before methods / inner classes - OK
private String _thing;
public String getMessage() {
return "Hello World!";
}
// Field declared after methods / inner classes - avoid this
private String _fieldInWrongLocation;
}
public static final String GOD_CLASS
public static final String EMPTY_CATCH_BLOCK
public void doSomething() {
try {
FileInputStream fis = new FileInputStream("/tmp/bugger");
} catch (IOException ioe) {
// not good
}
}
public static final String EMPTY_IF_STATEMENT
public class Foo {
void bar(int x) {
if (x == 0) {
// empty!
}
}
}
public static final String EMPTY_WHILE_STATEMENT
void bar(int a, int b) {
while (a == b) {
// empty!
}
}
public static final String EMPTY_TRY_BLOCK
public class Foo {
public void bar() {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static final String EMPTY_FINALLY_BLOCK
public class Foo {
public void bar() {
try {
int x = 2;
} finally {
// empty!
}
}
}
public static final String EMPTY_SWITCH_STATEMENTS
public void bar() {
int x = 2;
switch (x) {
// once there was code here
// but it's been commented out or something
}
}
public static final String EMPTY_SYNCHRONIZED_BLOCK
public class Foo {
public void bar() {
synchronized (this) {
// empty!
}
}
}
public static final String EMPTY_STATEMENT_NOT_IN_LOOP
public void doit() {
// this is probably not what you meant to do
;
// the extra semicolon here this is not necessary
System.out.println("look at the extra semicolon");
;
}
public static final String EMPTY_INITIALIZER
public class Foo {
static {
} // Why ?
{
} // Again, why ?
}
public static final String EMPTY_STATEMENT_BLOCK
public class Foo {
private int _bar;
public void setBar(int bar) {
{
_bar = bar;
} // Why not?
{
} // But remove this.
}
}
public static final String EMPTY_STATIC_INITIALIZER
public class Foo {
static {
// empty
}
}
public static final String EMPTY_FINANLIZER
public class Foo {
protected void finalize() {
}
}
public static final String FINALIZE_ONLY_CALLS_SUPER_FINALIZE
protected void finalize() {
super.finalize();
}
public static final String FINALIZE_OVERLOADED
public class Foo {
// this is confusing and probably a bug
protected void finalize(int a) {
}
}
public static final String FINALIZE_DOES_NOT_CALL_SUPER_FINALIZE
protected void finalize() {
something();
// neglected to call super.finalize()
}
public static final String FINALIZE_SHOULD_BE_PROTECTED
public void finalize() {
// do something
}
public static final String AVOID_CALLING_FINALIZE
void foo() {
Bar b = new Bar();
b.finalize();
}
public static final String DUPLICATE_IMPORTS
import java.lang.String; import java.lang.*;
public static final String DONT_IMPORT_JAVA_LANG
import java.lang.String; // this is unnecessary import java.lang.*; // this is bad
public static final String UNUSED_IMPORTS
// this is bad, if the class doesn't use java.io.File import java.io.File;
public static final String IMPORT_FROM_SAME_PACKAGE
package foo; import foo.Buz; // no need for this import foo.*; // or this
public static final String TOO_MANY_STATIC_IMPORTS
import static Lennon; import static Ringo; import static George; import static Paul; import static Yoko; // Too much !
public static final String UNNECESSARY_FULLY_QUALIFIED_NAME
public class Foo {
private java.util.List list1; // Unnecessary FQN
private List list2; // More appropriate given import of 'java.util.List'
}
public static final String USE_PROPER_CLASS_LOADER
public class Foo {
ClassLoader cl = Bar.class.getClassLoader();
}
public static final String MDB_AND_SESSION_BEAN_NAMING_CONVENTION
public class SomeBean implements SessionBean {
} // proper name
public class MissingTheProperSuffix implements SessionBean {
} // non-standard name
public static final String REMOTE_SESSION_INTERFACE_NAMING_CONVENTION
public interface MyBeautifulHome extends javax.ejb.EJBHome {
} // proper name
public interface MissingProperSuffix extends javax.ejb.EJBHome {
} // non-standard name
public static final String LOCAL_INTERFACE_SESSION_NAMING_CONVENTION
public interface MyLocal extends javax.ejb.EJBLocalObject {
} // proper name
public interface MissingProperSuffix extends javax.ejb.EJBLocalObject {
} // non-standard name
public static final String LOCAL_HOME_NAMING_CONVENTION
public interface MyBeautifulLocalHome extends javax.ejb.EJBLocalHome {
}// proper name
public interface MissingProperSuffix extends javax.ejb.EJBLocalHome {
} // non-standard name
public static final String REMOTE_INTERFACE_NAMING_CONVENTION
// Poor Session suffix
public interface BadSuffixSession extends javax.ejb.EJBObject {
}
// Poor EJB suffix
public interface BadSuffixEJB extends javax.ejb.EJBObject {
}
// Poor Bean suffix
public interface BadSuffixBean extends javax.ejb.EJBObject {
}
public static final String DO_NOT_CALL_SYSTEM_EXIT
public void bar() {
System.exit(0); // never call this when running in an application server!
}
public void foo() {
Runtime.getRuntime().exit(0); // never stop the JVM manually, the container will do this.
}
public static final String STATIC_EJB_FIELD_SHOULD_BE_FINAL
public class SomeEJB extends EJBObject implements EJBLocalHome {
private static int CountA; // poor, field can be edited
private static final int CountB; // preferred, read-only access
}
public static final String DO_NOT_USE_THREADS
// This is not allowed
public class UsingThread extends Thread {
}
// Neither this,
public class OtherThread implements Runnable {
// Nor this ...
public void methode() {
Runnable thread = new Thread();
thread.run();
}
}
public static final String BEAN_MEMBERS_SHOULD_SERIALIZE
public class Serialized {
private transient int someFoo; // good, it's transient
private static int otherFoo; // also OK
private int moreFoo; // OK, has proper accessors, see below
private int badFoo; // bad, should be
// marked transient
private void setMoreFoo(int moreFoo) {
this.moreFoo = moreFoo;
}
private int getMoreFoo() {
return this.moreFoo;
}
}
public static final String MISSING_SERIAL_VERSION_UID
public class Foo implements java.io.Serializable {
String name;
// Define serialization id to avoid serialization related bugs
// i.e., public static final long serialVersionUID = 4328743;
}
public static final String JUNIT_STATIC_SUITE
public class Foo extends TestCase {
public void suite() {
} // oops, should be static
private static void suite() {
} // oops, should be public
}
public static final String JUNIT_SPELLING
public class Foo extends TestCase {
public void setup() {
} // oops, should be setUp
public void TearDown() {
} // oops, should be tearDown
}
public static final String JUNIT_ASSERTIONS_SHOULD_INCLUDE_MESSAGE
public class Foo extends TestCase {
public void testSomething() {
assertEquals("foo", "bar");
// Use the form:
// assertEquals("Foo does not equals bar", "foo", "bar");
// instead
}
}
public static final String JUNIT_TESTS_SHOULD_INCLUDE_ASSERT
public class Foo extends TestCase {
public void testSomething() {
Bar b = findBar();
// This is better than having a NullPointerException
// assertNotNull("bar not found", b);
b.work();
}
}
public static final String TEST_CLASS_WITHOUT_TEST_CASES
// Consider changing the name of the class if it is not a test
// Consider adding test methods if it is a test
public class CarTest {
public static void main(String[] args) {
// do something
}
// code
}
public static final String UNNECESSARY_BOOLEAN_ASSERTION
public class SimpleTest extends TestCase {
public void testX() {
assertTrue(true); // serves no real purpose
}
}
public static final String USE_ASSERT_EQUALS_INSTEAD_OF_ASSERT_TRUE
public class FooTest extends TestCase {
void testCode() {
Object a, b;
assertTrue(a.equals(b)); // bad usage
assertEquals(a, b); // good usage
}
}
public static final String USE_ASSERT_SAME_INSTEAD_OF_ASSERT_TRUE
public class FooTest extends TestCase {
void testCode() {
Object a, b;
assertTrue(a == b); // bad usage
assertSame(a, b); // good usage
}
}
public static final String USE_ASSERT_NULL_INSTEAD_OF_ASSERT_TRUE
public class FooTest extends TestCase {
void testCode() {
Object a = doSomething();
assertTrue(a == null); // bad usage
assertNull(a); // good usage
assertTrue(a != null); // bad usage
assertNotNull(a); // good usage
}
}
public static final String SIMPLIFY_BOOLEAN_ASSERTION
public class SimpleTest extends TestCase {
public void testX() {
assertTrue("not empty", !r.isEmpty()); // replace with assertFalse("not empty", r.isEmpty())
assertFalse(!r.isEmpty()); // replace with assertTrue(r.isEmpty())
}
}
public static final String JUNIT_TEST_CONTAINS_TOO_MANY_ASSERTS
public class MyTestCase extends TestCase {
// Ok
public void testMyCaseWithOneAssert() {
boolean myVar = false;
assertFalse("should be false", myVar);
}
// Bad, too many asserts (assuming max=1)
public void testMyCaseWithMoreAsserts() {
boolean myVar = false;
assertFalse("myVar should be false", myVar);
assertEquals("should equals false", false, myVar);
}
}
public static final String USE_ASSERT_TRUE_INSTEAD_OF_ASSERT_EQUALS
public class MyTestCase extends TestCase {
public void testMyCase() {
boolean myVar = true;
// Ok
assertTrue("myVar is true", myVar);
// Bad
assertEquals("myVar is true", true, myVar);
// Bad
assertEquals("myVar is false", false, myVar);
}
}
public static final String USE_CORRECT_EXCEPTION_LOGGING
public class Main {
private static final Log _LOG = LogFactory.getLog(Main.class);
void bar() {
try {
} catch (Exception e) {
_LOG.error(e); // Wrong!
} catch (OtherException oe) {
_LOG.error(oe.getMessage(), oe); // Correct
}
}
}
public static final String PROPER_LOGGER
public class Foo {
private static final Log LOG = LogFactory.getLog(Foo.class); // proper way
protected Log LOG = LogFactory.getLog(Testclass.class); // wrong approach
}
public static final String GUARD_DEBUG_LOGGING
public class Test {
private static final Log __log = LogFactory.getLog(Test.class);
public void test() {
// okay:
__log.debug("log something");
// okay:
__log.debug("log something with exception", e);
// bad:
__log.debug("log something" + " and " + "concat strings");
// bad:
__log.debug("log something" + " and " + "concat strings", e);
// good:
if (__log.isDebugEnabled()) {
__log.debug("bla" + "", e);
}
}
}
public static final String MORE_THAN_ONE_LOGGER
public class Foo {
Logger log = Logger.getLogger(Foo.class.getName());
// It is very rare to see two loggers on a class, normally
// log information is multiplexed by levels
Logger log2 = Logger.getLogger(Foo.class.getName());
}
public static final String LOGGER_IS_NOT_STATIC_FINAL
public class Foo {
Logger log = Logger.getLogger(Foo.class.getName()); // not recommended
static final Logger log = Logger.getLogger(Foo.class.getName()); // preferred approach
}
public static final String SYSTEM_PRINTLN
class Foo {
Logger log = Logger.getLogger(Foo.class.getName());
public void testA() {
System.out.println("Entering test");
// Better use this
log.fine("Entering test");
}
}
public static final String AVOID_PRINT_STACK_TRACE
class Foo {
void bar() {
try {
// do something
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static final String REPLACE_VECTOR_WITH_LIST
public class Foo {
void bar() {
Vector v = new Vector();
}
}
public static final String REPLACE_HASHTABLE_WITH_MAP
public class Foo {
void bar() {
Hashtable h = new Hashtable();
}
}
public static final String REPLACE_ENUMERATION_WITH_ITERATOR
public class Foo implements Enumeration {
private int x = 42;
public boolean hasMoreElements() {
return true;
}
public Object nextElement() {
return String.valueOf(i++);
}
}
public static final String AVOID_ENUM_AS_IDENTIFIER
public class A {
public class foo {
String enum = "foo";
}
}
public static final String AVOID_ASSERT_AS_IDENTIFIER
public class A {
public class foo {
String assert = "foo";
}
}
public static final String INTEGER_INSTANTIATION
public class Foo {
private Integer i = new Integer(0); // change to Integer i = Integer.valueOf(0);
}
public static final String BYTE_INSTANTIATION
public class Foo {
private Byte i = new Byte(0); // change to Byte i = Byte.valueOf(0);
}
public static final String SHORT_INSTANTIATION
public class Foo {
private Short i = new Short(0); // change to Short i = Short.valueOf(0);
}
public static final String LONG_INSTANTIATION
public class Foo {
private Long i = new Long(0); // change to Long i = Long.valueOf(0);
}
public static final String JUNIT_4_TEST_SHOULD_USE_BEFORE_ANNOTATION
public class MyTest {
public void setUp() {
bad();
}
}
public class MyTest2 {
@Before
public void setUp() {
good();
}
}
public static final String JUNIT_4_TEST_SHOULD_USE_AFTER_ANNOTATION
public class MyTest {
public void tearDown() {
bad();
}
}
public class MyTest2 {
@After
public void tearDown() {
good();
}
}
public static final String JUNIT_4_TEST_SHOULD_USE_TEST_ANNOTATION
public class MyTest {
public void testBad() {
doSomething();
}
@Test
public void testGood() {
doSomething();
}
}
public static final String JUNIT_4_SUITES_SHOULD_USE_SUITE_ANNOTATION
public class BadExample extends TestCase {
public static Test suite() {
return new Suite();
}
}
@RunWith(Suite.class)
@SuiteClasses({ TestOne.class, TestTwo.class })
public class GoodTest {
}
public static final String JUNIT_USE_EXPECTED
public class MyTest {
@Test
public void testBad() {
try {
doSomething();
fail("should have thrown an exception");
} catch (Exception e) {
}
}
@Test(expected = Exception.class)
public void testGood() {
doSomething();
}
}
public static final String SHORT_VARIABLE
public class Something {
private int q = 15; // field - too short
public static void main(String as[]) { // formal arg - too short
int r = 20 + q; // local var - too short
for (int i = 0; i < 10; i++) { // not a violation (inside 'for' loop)
r += q;
}
}
}
public static final String LONG_VARIABLE
public class Something {
int reallyLongIntName = -3; // VIOLATION - Field
public static void main( String argumentsList[] ) { // VIOLATION - Formal
int otherReallyLongName = -5; // VIOLATION - Local
for (int interestingIntIndex = 0; // VIOLATION - For
interestingIntIndex < 10;
interestingIntIndex ++ ) {
}
}
public static final String SHORT_METHOD_NAME
public class ShortMethod {
public void a(int i) { // Violation
}
}
public static final String VARIABLE_NAMING_CONVENTIONS
public class Foo {
public static final int MY_NUM = 0;
public String myTest = "";
DataModule dmTest = new DataModule();
}
public static final String METHOD_NAMING_CONVENTIONS
public class Foo {
public void fooStuff() {
}
}
public static final String CLASS_NAMING_CONVENTIONS
public class Foo {
}
public static final String ABSTRACT_NAMING
public abstract class Foo { // should be AbstractFoo
}
public static final String AVOID_DOLLAR_SIGNS
public class Fo$o { // not a recommended name
}
public static final String METHOD_WITH_SAME_NAME_AS_ENCLOSING_CLASS
public class MyClass {
public MyClass() {
} // this is OK because it is a constructor
public void MyClass() {
} // this is bad because it is a method
}
public static final String SUSPICIOUS_HASHCODE_METHOD_NAME
public class Foo {
public int hashcode() { // oops, this probably was supposed to be 'hashCode'
}
}
public static final String SUSPICIOUS_CONSTANT_FIELD_NAME
public class Foo {
// this is bad, since someone could accidentally
// do PI = 2.71828; which is actually e
// final double PI = 3.16; is ok
double PI = 3.16;
}
public static final String SUSPICIOUS_EQUALS_METHOD_NAME
public class Foo {
public int equals(Object o) {
// oops, this probably was supposed to be boolean equals
}
public boolean equals(String s) {
// oops, this probably was supposed to be equals(Object)
}
public boolean equals(Object o1, Object o2) {
// oops, this probably was supposed to be equals(Object)
}
}
public static final String AVOID_FIELD_NAME_MATCHING_TYPE_NAME
public class Foo extends Bar {
int foo; // There is probably a better name that can be used
}
public static final String AVOID_FIELD_NAME_MATCHING_METHOD_NAME
public class Foo {
Object bar;
// bar is data or an action or both?
void bar() {
}
}
public static final String NO_PACKAGE
// no package declaration
public class ClassInDefaultPackage {
}
public static final String PACKAGE_CASE
package com.MyCompany; // should be lowercase name
public static final String MISLEADING_VARIABLE_NAME
public class Foo {
private int m_foo; // OK
public void bar(String m_baz) { // Bad
int m_boz = 42; // Bad
}
}
public static final String BOOLEAN_GET_METHOD_NAME
public boolean getFoo(); // bad public boolean isFoo(); // ok public boolean getFoo(boolean bar); // ok, unless checkParameterizedMethods=true
public static final String SHORT_CLASS_NAME
public class Foo {
}
public static final String GENERICS_NAMING
public interface GenericDao<E extends BaseModel, K extends Serializable> extends BaseDao {
// This is ok...
}
public interface GenericDao<E extends BaseModel, K extends Serializable> {
// Also this
}
public interface GenericDao<e extends BaseModel, K extends Serializable> {
// 'e' should be an 'E'
}
public interface GenericDao<EF extends BaseModel, K extends Serializable> {
// 'EF' is not ok.
}
public static final String LOCAL_VARIABLE_COULD_BE_FINAL
public class Bar {
public void foo() {
String txtA = "a"; // if txtA will not be assigned again it is better to do this:
final String txtB = "b";
}
}
public static final String METHOD_ARGUMENT_COULD_BE_FINAL
public void foo1(String param) { // do stuff with param never assigning it
}
public void foo2(final String param) { // better, do stuff with param never assigning it
}
public static final String AVOID_INSTANTIATING_OBJECTS_IN_LOOPS
public class Something {
public static void main(String as[]) {
for (int i = 0; i < 10; i++) {
Foo f = new Foo(); // Avoid this whenever you can it's really expensive
}
}
}
public static final String USE_ARRAY_LIST_INSTEAD_OF_VECTOR
public class SimpleTest extends TestCase {
public void testX() {
Collection c1 = new Vector();
Collection c2 = new ArrayList(); // achieves the same with much better performance
}
}
public static final String SIMPLIFY_STARTS_WITH
public class Foo {
boolean checkIt(String x) {
return x.startsWith("a"); // suboptimal
}
boolean fasterCheckIt(String x) {
return x.charAt(0) == 'a'; // faster approach
}
}
public static final String USE_STRING_BUFFER_FOR_STRING_APPENDS
public class Foo {
void bar() {
String a;
a = "foo";
a += " bar";
// better would be:
// StringBuilder a = new StringBuilder("foo");
// a.append(" bar);
}
}
public static final String USE_ARRAYS_AS_LIST
public class Test {
public void foo(Integer[] ints) {
// could just use Arrays.asList(ints)
List l = new ArrayList(10);
for (int i = 0; i < 100; i++) {
l.add(ints[i]);
}
for (int i = 0; i < 100; i++) {
l.add(a[i].toString()); // won't trigger the rule
}
}
}
public static final String AVOID_ARRAY_LOOPS
public class Test {
public void bar() {
int[] a = new int[10];
int[] b = new int[10];
for (int i=0;i<10;i++) {
b[i]=a[i];
}
}
}
// this will trigger the rule
for (int i=0;i<10;i++) {
b[i]=a[c[i]];
}
}
}
public static final String UNNECESSARY_WRAPPER_OBJECT_CREATION
public int convert(String s) {
int i, i2;
i = Integer.valueOf(s).intValue(); // this wastes an object
i = Integer.parseInt(s); // this is better
i2 = Integer.valueOf(i).intValue(); // this wastes an object
i2 = i; // this is better
String s3 = Integer.valueOf(i2).toString(); // this wastes an object
s3 = Integer.toString(i2); // this is better
return i2;
}
public static final String ADD_EMPTY_STRING
// inefficient String s = "" + 123;
public static final String REDUNDANT_FIELD_INITIALIZER
public class C {
boolean b = false; // examples of redundant initializers
byte by = 0;
short s = 0;
char c = 0;
int i = 0;
long l = 0;
float f = .0f; // all possible float literals
doable d = 0d; // all possible double literals
Object o = null;
MyClass mca[] = null;
int i1 = 0, ia1[] = null;
class Nested {
boolean b = false;
}
}
public static final String PREMATURE_DECLARATION
public int getLength(String[] strings) {
int length = 0; // declared prematurely
if (strings == null || strings.length == 0)
return 0;
for (String str : strings) {
length += str.length();
}
return length;
}
public static final String AVOID_CATCHING_THROWABLE
public void bar() {
try {
// do something
} catch (Throwable th) { // should not catch Throwable
th.printStackTrace();
}
}
public static final String SIGNATURE_DECLARE_THROWS_EXCEPTION
public void foo() throws Exception {
}
public static final String EXCEPTION_AS_FLOW_CONTROL
public void bar() {
try {
try {
} catch (Exception e) {
throw new WrapperException(e);
// this is essentially a GOTO to the WrapperException catch block
}
} catch (WrapperException e) {
// do some more stuff
}
}
public static final String AVOID_CATCHING_NPE
public class Foo {
void bar() {
try {
// do something
} catch (NullPointerException npe) {
}
}
}
public static final String AVOID_THROWING_RAW_EXCEPTION_TYPES
public class Foo {
public void bar() throws Exception {
throw new Exception();
}
}
public static final String AVOID_THROWING_NULL_POINTER_EXCEPTION
public class Foo {
void bar() {
throw new NullPointerException();
}
}
public static final String AVOID_RETHROWING_EXCEPTION
public void bar() {
try {
// do something
} catch (SomeException se) {
throw se;
}
}
public static final String DO_NOT_EXTEND_JAVA_LANG_ERROR
public class Foo extends Error {
}
public static final String DO_NOT_THROW_EXCEPTION_IN_FINALLY
public class Foo {
public void bar() {
try {
// Here do some stuff
} catch (Exception e) {
// Handling the issue
} finally {
// is this really a good idea ?
throw new Exception();
}
}
}
public static final String AVOID_THROWING_NEW_INSTANCE_OF_SAME_EXCEPTION
public void bar() {
try {
// do something
} catch (SomeException se) {
// harmless comment
throw new SomeException(se);
}
}
public static final String AVOID_CATCHING_GENERIC_EXCEPTION
public class PrimitiveType {
public void downCastPrimitiveType() {
try {
System.out.println(" i [" + i + "]");
} catch (Exception e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public static final String AVOID_LOSING_EXCEPTION_INFORMATION
public void bar() {
try {
// do something
} catch (SomeException se) {
se.getMessage();
}
}
public static final String AVOID_DUPLICATE_LITERALS
private void bar() {
buz("Howdy");
buz("Howdy");
buz("Howdy");
buz("Howdy");
}
public static final String STRING_INSTANTIATION
private String bar = new String("bar"); // just do a String bar = "bar";
public static final String STRING_TO_STRING
private String baz() {
String bar = "howdy";
return bar.toString();
}
public static final String INEFFICIENT_STRING_BUFFERING
// Avoid this, two buffers are actually being created here
StringBuffer sb = new StringBuffer("tmp = " + System.getProperty("java.io.tmpdir"));
// do this instead
StringBuffer sb = new StringBuffer("tmp = ");
sb.append(System.getProperty("java.io.tmpdir"));
public static final String UNNECESSARY_CASE_CHANGE
boolean answer1 = buz.toUpperCase().equals("baz"); // should be buz.equalsIgnoreCase("baz")
public static final String USE_STRING_BUFFER_LENGTH
StringBuffer sb = new StringBuffer();
if (sb.toString().equals("")) {
} // inefficient
if (sb.length() == 0) {
} // preferred
public static final String APPEND_CHARACTER_WITH_CHAR
StringBuffer sb = new StringBuffer();
sb.append("a"); // avoid this
StringBuffer sb = new StringBuffer();
sb.append('a'); // use this instead
public static final String CONSECUTIVE_LITERAL_APPENDS
StringBuffer buf = new StringBuffer();
buf.append("Hello").append(" ").append("World"); // poor
buf.append("Hello World"); // good
public static final String USE_INDEX_OF_CHAR
String s = "hello world";
// avoid this
if (s.indexOf("d") {}
// instead do this
if (s.indexOf('d') {}
public static final String INEFFICIENT_EMPTY_STRING_CHECK
public void bar(String string) {
if (string != null && string.trim().size() > 0) {
doSomething();
}
}
public static final String INSUFFICIENT_STRING_BUFFER_DECLARATION
StringBuffer bad = new StringBuffer();
bad.append("This is a long string that will exceed the default 16 characters");
StringBuffer good = new StringBuffer(41);
good.append("This is a long string, which is pre-sized");
public static final String USELESS_STRING_VALUE_OF
public String convert(int i) {
String s;
s = "a" + String.valueOf(i); // not required
s = "a" + i; // preferred approach
return s;
}
public static final String STRING_BUFFER_INSTANTIATION_WITH_CHAR
public static final String USE_EQUALS_TO_COMPARE_STRINGS
public boolean test(String s) {
if (s == "one")
return true; // unreliable
if ("two".equals(s))
return true; // better
return false;
}
public static final String AVOID_STRING_BUFFER_FIELD
public class Foo {
private StringBuffer buffer; // potential memory leak as an instance variable;
}
public static final String METHOD_RETURNS_INTERNAL_ARRAY
public class SecureSystem {
UserData[] ud;
public UserData[] getUserData() {
// Don't return directly the internal array, return a copy
return ud;
}
}
public static final String ARRAY_IS_STORED_DIRECTLY
public class Foo {
private String[] x;
public void foo(String[] param) {
// Don't do this, make a copy of the array at least
this.x = param;
}
}
public static final String UNNECESSARY_CONVERSION_TEMPORARY
public String convert(int x) {
String foo = new Integer(x).toString(); // this wastes an object
return Integer.toString(x); // preferred approach
}
public static final String UNNECESSARY_RETURN
public class Foo {
public void bar() {
int x = 42;
return;
}
}
public static final String UNNECESSARY_FINAL_MODIFIER
public final class Foo {
// This final modifier is not necessary, since the class is final
// and thus, all methods are final
private final void foo() {
}
}
public static final String USELESS_OVERRIDING_METHOD
public void foo(String bar) {
super.foo(bar); // why bother overriding?
}
public String foo() {
return super.foo(); // why bother overriding?
}
@Id
public Long getId() {
return super.getId(); // OK if 'ignoreAnnotations' is false, which is the default behavior
}
public static final String USELESS_OPERATION_ON_IMMUTABLE
class Test {
void method1() {
BigDecimal bd = new BigDecimal(10);
bd.add(new BigDecimal(5)); // this will trigger the rule
}
void method2() {
BigDecimal bd = new BigDecimal(10);
bd = bd.add(new BigDecimal(5)); // this won't trigger the rule
}
}
public static final String UNUSED_NULL_CHECK_IN_EQUALS
public class Test {
public String method1() {
return "ok";
}
public String method2() {
return null;
}
public void method(String a) {
String b;
// I don't know it method1() can be "null"
// but I know "a" is not null..
// I'd better write a.equals(method1())
if (a != null && method1().equals(a)) { // will trigger the rule
// whatever
}
if (method1().equals(a) && a != null) { // won't trigger the rule
// whatever
}
if (a != null && method1().equals(b)) { // won't trigger the rule
// whatever
}
if (a != null && "LITERAL".equals(a)) { // won't trigger the rule
// whatever
}
if (a != null && !a.equals("go")) { // won't trigger the rule
a = method2();
if (method1().equals(a)) {
// whatever
}
}
}
}
public static final String USELESS_PARANTHESES
public class Foo {
private int _bar1;
private Integer _bar2;
public void setBar(int n) {
_bar1 = Integer.valueOf((n)); // here
_bar2 = (n); // and here
}
}
public static final String UNUSED_PRIVATE_FIELD
public class Something {
private static int FOO = 2; // Unused
private int i = 5; // Unused
private int j = 6;
public int addOne() {
return j++;
}
}
public static final String UNUSED_LOCAL_VARIABLE
public class Foo {
public void doSomething() {
int i = 5; // Unused
}
}
public static final String UNUSED_PRIVATE_METHOD
public class Something {
private void foo() {
} // unused
}
public static final String UNUSED_FORMAL_PARAMETER
public class Foo {
private void bar(String howdy) {
// howdy is not used
}
}
public static final String UNUSED_MODIFIER
public interface Foo {
public abstract void bar(); // both abstract and public are ignored by the compiler
public static final int X = 0; // public, static, and final all ignored
public static class Bar {
} // public, static ignored
public static interface Baz {
} // ditto
}
public class Bar {
public static interface Baz {
} // static ignored
}
Copyright © 2013. All rights reserved.