Rule Description KPI url
JumbledIncrementer Avoid jumbled loop incrementers – its usually a mistake, and is confusing even if intentional. Understandability
ForLoopShouldBeWhileLoop Some for loops can be simplified to while loops, this makes them more concise. Understandability
ReturnFromFinallyBlock Avoid returning from a finally block, this can discard exceptions. Analyzability
UnconditionalIfStatement Do not use “if” statements whose conditionals are always true or always false. Understandability
BooleanInstantiation Avoid instantiating Boolean objects; you can reference Boolean.TRUE, Boolean.FALSE, or call Boolean.valueOf() instead. Understandability
CollapsibleIfStatements Sometimes two consecutive ‘if’ statements can be consolidated by separating their conditions with a boolean short-circuit operator. Efficiency
ClassCastExceptionWithToArray 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. Doing otherwise you will resultin a ClassCastException. Robustness
AvoidDecimalLiteralsInBigDecimalConstructor   Accuracy
MisplacedNullCheck The null check here is misplaced. If the variable is null a NullPointerException will be thrown. Either the check is useless (the variable will never be “null”) or it is incorrect. Robustness
AvoidThreadGroup Avoid using java.lang.ThreadGroup; although it is intended to be used in a threaded environment it contains methods that are not thread-safe. Robustness
BigIntegerInstantiation 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) Understandability
AvoidUsingOctalValues Integer literals should not start with zero since this denotes that the rest of literal will be interpreted as an octal value. Accuracy
AvoidUsingHardCodedIP Application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP adresses is preferable. Portability
CheckResultSet Always check the return values of navigation methods (next, previous, first, last) of a ResultSet. If the value return is ‘false’, it should be handled properly. Robustness
CheckSkipResult The skip() method may skip a smaller number of bytes than requested. Check the returned value to find out if it was the case or not. Accuracy
DontUseFloatTypeForLoopIndices Don’t use floating point for loop indices. If you must use floating point, use double unless you’re certain that float provides enough precision and you have a compelling performance need (space or time). Accuracy
SimplifiedTernary Look for ternary operators with the form condition ? literalBoolean : foo or condition ? foo : literalBoolean. These expressions can be simplified respectively to condition || foo when the literalBoolean is true !condition && foo when the literalBoolean is false or !condition || foo when the literalBoolean is true condition && foo when the literalBoolean is false Understandability
IfStmtsMustUseBraces Avoid using if statements without using braces to surround the code block. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest. Understandability
WhileLoopsMustUseBraces Avoid using ‘while’ statements without using braces to surround the code block. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest. Understandability
IfElseStmtsMustUseBraces Avoid using if..else statements without using surrounding braces. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest. Understandability
ForLoopsMustUseBraces Avoid using ‘for’ statements without using curly braces. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest. Understandability
CloneThrowsCloneNotSupportedException The method clone() should throw a CloneNotSupportedException. Understandability
CloneMethodMustImplementCloneable 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. Understandability
CloneMethodReturnTypeMustMatchClassName If a class implements cloneable the return type of the method clone() must be the class name. That way, the caller of the clone method doesn’t need to cast the returned clone to the correct type. Note: This is only possible with Java 1.5 or higher. Understandability
CloneMethodMustBePublic The java Manual says “By convention, classes that implement this interface should override Object.clone (which is protected) with a public method.” Understandability
NPathComplexity The NPath complexity of a method is the number of acyclic execution paths through that method. A threshold of 200 is generally considered the point where measures should be taken to reduce complexity and increase readability. Maintainability
ExcessiveMethodLength When methods are excessively long this usually indicates that the method is doing more than its name/signature might suggest. They also become challenging for others to digest since excessive scrolling causes readers to lose focus. Try to reduce the method length by creating helper methods and removing any copy/pasted code. Maintainability
ExcessiveParameterList Methods with numerous parameters are a challenge to maintain, especially if most of them share the same datatype. These situations usually denote the need for new objects to wrap the numerous parameters. Maintainability
ExcessiveClassLength 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. In breaking these methods apart the code becomes more managable and ripe for reuse. Maintainability
ExcessivePublicCount Classes with large numbers of public methods and attributes require disproportionate testing efforts since combinational side effects grow rapidly and increase risk. Refactoring these classes into smaller ones not only increases testability and reliability but also allows new variations to be developed easily. Maintainability
TooManyFields 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. For example, a class with individual city/state/zip fields could park them within a single Address field. Maintainability
NcssMethodCount This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for a given method. NCSS ignores comments, and counts actual statements. Using this algorithm, lines of code that are split are counted as one. Maintainability
NcssTypeCount This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for a given type. NCSS ignores comments, and counts actual statements. Using this algorithm, lines of code that are split are counted as one. Maintainability
NcssConstructorCount This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for a given constructor. NCSS ignores comments, and counts actual statements. Using this algorithm, lines of code that are split are counted as one. Maintainability
TooManyMethods 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. Maintainability
CommentDefaultAccessModifier To avoid mistakes if we want that a Method, Field or Nested class have a default access modifier we must add a comment at the beginning of the Method, Field or Nested class. By default the comment must be /* default */, if you want another, you have to provide a regex. Maintainability
UnnecessaryConstructor 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. Understandability
NullAssignment Assigning a “null” to a variable (outside of its declaration) is usually bad form. Sometimes, this type of assignment is an indication that the programmer doesn’t completely understand what is going on in the code. NOTE: This sort of assignment may used in some cases to dereference objects and encourage garbage collection. Maintainability
OnlyOneReturn A method should have only one exit point, and that should be the last statement in the method. Understandability
AssignmentInOperand Avoid assignments in operands; this can make code more complicated and harder to read. Understandability
AtLeastOneConstructor Each class should declare at least one constructor. Understandability
SuspiciousOctalEscape A suspicious octal escape sequence was found inside a String literal. The Java language specification (section 3.10.6) says an octal escape sequence inside a literal String shall consist of a backslash followed by: OctalDigit | OctalDigit OctalDigit | ZeroToThree OctalDigit OctalDigit Any octal escape sequence followed by non-octal digits can be confusing, e.g. “38” is interpreted as the octal escape sequence “3” followed by the literal character “8”. Maintainability
CallSuperInConstructor It is a good practice to call super() in a constructor. If super() is not called but another constructor (such as an overloaded constructor) is called, this rule will not report it. Maintainability
DefaultPackage Use explicit scoping instead of accidental usage of default package private level. The rule allows methods and fields annotated with Guava’s @VisibleForTesting. Maintainability
AvoidFinalLocalVariable Avoid using final local variables, turn them into fields. Understandability
AvoidAccessibilityAlteration 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. This violates the principle of encapsulation. Maintainability
AvoidLiteralsInIfCondition Avoid using hard-coded literals in conditional statements. By declaring them as static variables or private members with descriptive names maintainability is enhanced. By default, the literals “-1” and “0” are ignored. More exceptions can be defined with the property “ignoreMagicNumbers”. Understandability
UseObjectForClearerAPI When you write a public method, you should be thinking in terms of an API. If your method is public, it means other class will use it, therefore, you want (or need) to offer a comprehensive and evolutive API. If you pass a lot of information as a simple series of Strings, you may think of using an Object to represent all those information. You’ll get a simpler API (such as doWork(Workload workload), rather than a tedious series of Strings) and more importantly, if you need at some point to pass extra data, you’ll be able to do so by simply modifying or extending Workload without any modification to your API. Understandability
UseConcurrentHashMap Since Java5 brought a new implementation of the Map designed for multi-threaded access, you can perform efficient map reads without blocking other threads. Efficiency
CouplingBetweenObjects This rule counts the number of unique attributes, local variables, and return types within an object. A number higher than the specified threshold can indicate a high degree of coupling. Understandability
ExcessiveImports A high number of imports can indicate a high degree of coupling within an object. This rule counts the number of unique imports and reports a violation if the count is above the user-specified threshold. Understandability
LooseCoupling The use of implementation types as object references limits your ability to use alternate implementations in the future as requirements change. Whenever available, referencing objects by their interface types provides much more flexibility. Changeability
LoosePackageCoupling Avoid using classes from the configured package hierarchy outside of the package hierarchy, except when using one of the configured allowed classes. Understandability
LawOfDemeter The Law of Demeter is a simple rule, that says “only talk to friends”. It helps to reduce coupling between classes or objects. Maintainability
UseUtilityClass For classes that only have static methods, consider making them utility classes. Note that this doesn’t apply to abstract classes, since their subclasses may well include non-static methods. Also, if you want this class to be a utility class, remember to add a private constructor to prevent instantiation. (Note, that this use was known before PMD 5.1.0 as UseSingleton). Understandability
SimplifyBooleanReturns Avoid unnecessary if-then-else statements when returning a boolean. The result of the conditional test can be returned instead. Understandability
SimplifyBooleanExpressions Avoid unnecessary comparisons in boolean expressions, they serve no purpose and impacts readability. Understandability
SwitchStmtsShouldHaveDefault All switch statements should include a default option to catch any unspecified values. Maintainability
AvoidDeeplyNestedIfStmts Avoid creating deeply nested if-then statements since they are harder to read and error-prone to maintain. Understandability
SwitchDensity A high ratio of statements to labels in a switch statement implies that the switch statement is overloaded. Consider moving the statements into new methods or creating subclasses based on the switch variable. Understandability
AccessorClassGeneration Instantiation by way of private constructors from outside of the constructor’s class often causes the generation of an accessor. A factory method, or non-privatization of the constructor can eliminate this situation. The generated class file is actually an interface. It gives the accessing class the ability to invoke a new hidden package scope constructor that takes the interface as a supplementary parameter. This turns a private constructor effectively into one with package scope, and is challenging to discern. Understandability
FinalFieldCouldBeStatic If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime. Efficiency
NonStaticInitializer A non-static initializer block will be called any time a constructor is invoked (just prior to invoking the constructor). While this is a valid language construct, it is rarely used and is confusing. Understandability
DefaultLabelNotLastInSwitchStmt By convention, the default label should be the last label in a switch statement. Understandability
NonCaseLabelInSwitchStatement A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but confusing. It is easy to mix up the case labels and the non-case labels. Understandability
OptimizableToArrayCall Calls to a collection’s toArray() method should specify target arrays sized to match the size of the collection. Initial arrays that are too small are discarded in favour of new ones that have to be created that are the proper size. Efficiency
BadComparison Avoid equality comparisons with Double.NaN. Due to the implicit lack of representation precision when comparing floating point numbers these are likely to cause logic errors. Accuracy
IdempotentOperations Avoid idempotent operations – they have no effect. Understandability
SimpleDateFormatNeedsLocale Be sure to specify a Locale when creating SimpleDateFormat instances to ensure that locale-appropriate formatting is used. Portability
ImmutableField Identifies private fields whose values never change once they are initialized either in the declaration of the field or by a constructor. This helps in converting existing classes to becoming immutable ones. Understandability
UseLocaleWithCaseConversions When doing String.toLowerCase()/toUpperCase() conversions, use Locales to avoids problems with languages that have unusual conventions, i.e. Turkish. Portability
AvoidProtectedFieldInFinalClass Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent by using private or package access modifiers instead. Understandability
AssignmentToNonFinalStatic Identifies a possible unsafe usage of a static field. Maintainability
MissingStaticMethodInNonInstantiatableClass A class that has private constructors and does not have any static methods or fields cannot be used. Understandability
UseNotifyAllInsteadOfNotify Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only one is chosen. The thread chosen is arbitrary; thus its usually safer to call notifyAll() instead. Understandability
AvoidInstanceofChecksInCatchClause Each caught exception type should be handled in its own catch clause. Understandability
AbstractClassWithoutAbstractMethod The abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods. If the class is intended to be used as a base class only (not to be instantiated directly) a protected constructor can be provided prevent direct instantiation. Understandability
SimplifyConditional No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument. Understandability
PositionLiteralsFirstInComparisons Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false. Robustness
PositionLiteralsFirstInCaseInsensitiveComparisons Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false. Robustness
UncommentedEmptyMethodBody Uncommented Empty Method Body finds instances where a method body does not contain statements, but there is no comment. By explicitly commenting empty method bodies it is easier to distinguish between intentional (commented) and unintentional empty methods. Understandability
UncommentedEmptyConstructor Uncommented Empty Constructor finds instances where a constructor does not contain statements, but there is no comment. By explicitly commenting empty constructors it is easier to distinguish between intentional (commented) and unintentional empty constructors. Understandability
AvoidConstantsInterface 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. Understandability
UnsynchronizedStaticDateFormatter SimpleDateFormat instances are not synchronized. Sun recommends using separate format instances for each thread. If multiple threads must access a static formatter, the formatter must be synchronized either on method or block level. Robustness
PreserveStackTrace 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. Analyzability
UseCollectionIsEmpty The isEmpty() method on java.util.Collection is provided to determine if a collection has any elements. Comparing the value of size() to 0 does not convey intent as well as the isEmpty() method. Efficiency
ClassWithOnlyPrivateConstructorsShouldBeFinal A class with only private constructors should be final, unless the private constructor is invoked by a inner class. Maintainability
EmptyMethodInAbstractClassShouldBeAbstract Empty or auto-generated methods in an abstract class should be tagged as abstract. This helps to remove their inapproprate usage by developers who should be implementing their own versions in the concrete subclasses. Maintainability
SingularField Fields whose scopes are limited to just single methods do not rely on the containing object to provide them to other methods. They may be better implemented as local variables within those methods. Understandability
TooFewBranchesForASwitchStatement Switch statements are indended to be used to support complex branching behaviour. Using a switch for only a few cases is ill-advised, since switches are not as easy to understand as if-then statements. In these cases use the if-then statement to increase code readability. Efficiency
LogicInversion Use opposite operator instead of negating the whole expression with a logic complement operator. Understandability
FieldDeclarationsShouldBeAtStartOfClass Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes. Understandability
AvoidProtectedMethodInFinalClassNotExtending Do not use protected methods in most final classes since they cannot be subclassed. This should only be allowed in final classes that extend other classes with protected methods (whose visibility cannot be reduced). Clarify your intent by using private or package access modifiers instead. Understandability
ConstantsInInterface Avoid constants in interfaces. Interfaces should define types, constants are implementation details better placed in classes or enums. See Effective Java, item 19. Understandability
EmptyCatchBlock Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this swallows an exception which should either be acted on or reported. Analyzability
EmptyIfStmt Empty If Statement finds instances where a condition is checked but nothing is done about it. Understandability
EmptyWhileStmt Empty While Statement finds all instances where a while statement does nothing. If it is a timing loop, then you should use Thread.sleep() for it; if it is a while loop that does a lot in the exit expression, rewrite it to make it clearer. Understandability
EmptyTryBlock Avoid empty try blocks – what’s the point? Understandability
EmptyFinallyBlock Empty finally blocks serve no purpose and should be removed. Understandability
EmptySwitchStatements Empty switch statements serve no purpose and should be removed. Understandability
EmptySynchronizedBlock Empty synchronized blocks serve no purpose and should be removed. Understandability
EmptyStatementNotInLoop 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. It could also be a double semicolon, which has no purpose and should be removed. Accuracy
EmptyInitializer Empty initializers serve no purpose and should be removed. Understandability
EmptyStatementBlock Empty block statements serve no purpose and should be removed. Understandability
EmptyStaticInitializer An empty static initializer serve no purpose and should be removed. Understandability
EmptyFinalizer Empty finalize methods serve no purpose and should be removed. Understandability
FinalizeOnlyCallsSuperFinalize If the finalize() is implemented, it should do something besides just calling super.finalize(). Understandability
FinalizeOverloaded Methods named finalize() should not have parameters. It is confusing and most likely an attempt to overload Object.finalize(). It will not be called by the VM. Understandability
FinalizeDoesNotCallSuperFinalize If the finalize() is implemented, its last action should be to call super.finalize. Resource Utilization
FinalizeShouldBeProtected When overriding the finalize(), the new method should be set as protected. If made public, other classes may invoke it at inappropriate times. Maintainability
AvoidCallingFinalize 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. It should not be invoked by application logic. Maintainability
ImportFromSamePackage There is no need to import a type that lives in the same package. Understandability
TooManyStaticImports 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. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from (Sun 1.5 Language Guide). Understandability
UseProperClassLoader In J2EE, the getClassLoader() method might not work as expected. Use Thread.currentThread().getContextClassLoader() instead. Accuracy
DoNotCallSystemExit Web applications should not call System.exit(), since only the web container or the application server should stop the JVM. This rule also checks for the equivalent call Runtime.getRuntime().exit(). Maintainability
StaticEJBFieldShouldBeFinal According to the J2EE specification, an EJB should not have any static fields with write access. However, static read-only fields are allowed. This ensures proper behavior especially when instances are distributed by the container on several JREs. Maintainability
DoNotUseThreads The J2EE specification explicitly forbids the use of threads. Maintainability
BeanMembersShouldSerialize If a class is a bean, or is referenced by a bean directly or indirectly it needs to be serializable. Member variables need to be marked as transient, static, or have accessor methods in the class. Marking variables as transient is the safest and easiest modification. Accessor methods should follow the Java naming conventions, i.e. for a variable named foo, getFoo() and setFoo() accessor methods should be provided. Understandability
MissingSerialVersionUID Serializable classes should provide a serialVersionUID field. Robustness
JUnitStaticSuite The suite() method in a JUnit test needs to be both public and static. Understandability
JUnitSpelling Some JUnit framework methods are easy to misspell. Accuracy
JUnitAssertionsShouldIncludeMessage JUnit assertions should include an informative message – i.e., use the three-argument version of assertEquals(), not the two-argument version. Understandability
JUnitTestsShouldIncludeAssert JUnit tests should include at least one assertion. This makes the tests more robust, and using assert with messages provide the developer a clearer idea of what the test does. Understandability
TestClassWithoutTestCases Test classes end with the suffix Test. Having a non-test class with that name is not a good practice, since most people will assume it is a test case. Test classes have test methods named testXXX. Understandability
UnnecessaryBooleanAssertion A JUnit test assertion with a boolean literal is unnecessary since it always will evaluate to the same thing. Consider using flow control (in case of assertTrue(false) or similar) or simply removing statements like assertTrue(true) and assertFalse(false). If you just want a test to halt after finding an error, use the fail() method and provide an indication message of why it did. Understandability
UseAssertEqualsInsteadOfAssertTrue This rule detects JUnit assertions in object equality. These assertions should be made by more specific methods, like assertEquals. Understandability
UseAssertSameInsteadOfAssertTrue This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertSame, assertNotSame. Understandability
UseAssertNullInsteadOfAssertTrue This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertNull, assertNotNull. Understandability
SimplifyBooleanAssertion Avoid negation in an assertTrue or assertFalse test. For example, rephrase: assertTrue(!expr); as: assertFalse(expr); Understandability
JUnitTestContainsTooManyAsserts JUnit tests should not contain too many asserts. Many asserts are indicative of a complex test, for which it is harder to verify correctness. Consider breaking the test scenario into multiple, shorter test scenarios. Customize the maximum number of assertions used by this Rule to suit your needs. Understandability
UseAssertTrueInsteadOfAssertEquals When asserting a value is the same as a literal or Boxed boolean, use assertTrue/assertFalse, instead of assertEquals. Robustness
UseCorrectExceptionLogging To make sure the full stacktrace is printed out, use the logging statement with two arguments: a String and a Throwable. Analyzability
ProperLogger A logger should normally be defined private static final and be associated with the correct class. Private final Log log; is also allowed for rare cases where loggers need to be passed around, with the restriction that the logger needs to be passed into the constructor. Analyzability
GuardDebugLogging When log messages are composed by concatenating strings, the whole section should be guarded by a isDebugEnabled() check to avoid performance and memory issues. Analyzability
AvoidPrintStackTrace Avoid printStackTrace(); use a logger call instead. Understandability
ReplaceVectorWithList Consider replacing Vector usages with the newer java.util.ArrayList if expensive thread-safe operations are not required. Maintainability
ReplaceHashtableWithMap Consider replacing Hashtable usage with the newer java.util.Map if thread safety is not required. Maintainability
ReplaceEnumerationWithIterator Consider replacing Enumeration usages with the newer java.util.Iterator Maintainability
JUnit4TestShouldUseBeforeAnnotation In JUnit 3, the setUp method was used to set up all data entities required in running tests. JUnit 4 skips the setUp method and executes all methods annotated with @Before before all tests Understandability
JUnit4TestShouldUseAfterAnnotation In JUnit 3, the tearDown method was used to clean up all data entities required in running tests. JUnit 4 skips the tearDown method and executes all methods annotated with @After after running each test Understandability
JUnit4TestShouldUseTestAnnotation In JUnit 3, the framework executed all methods which started with the word test as a unit test. In JUnit 4, only methods annotated with the @Test annotation are executed. Understandability
JUnit4SuitesShouldUseSuiteAnnotation In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicated through the @RunWith(Suite.class) annotation. Understandability
JUnitUseExpected In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions. Understandability
ShortVariable Fields, local variables, or parameter names that are very short are not helpful to the reader. Understandability
LongVariable Fields, formal arguments, or local variable names that are too long can make the code difficult to follow. Understandability
ShortMethodName Method names that are very short are not helpful to the reader. Understandability
AbstractNaming Abstract classes should be named ‘AbstractXXX’. Understandability
AvoidDollarSigns Avoid using dollar signs in variable/method/class/interface names. Understandability
MethodWithSameNameAsEnclosingClass Non-constructor methods should not have the same name as the enclosing class. Understandability
SuspiciousHashcodeMethodName The method name and return type are suspiciously close to hashCode(), which may denote an intention to override the hashCode() method. Understandability
SuspiciousConstantFieldName Field names using all uppercase characters – Sun’s Java naming conventions indicating constants – should be declared as final. Understandability
AvoidFieldNameMatchingTypeName It is somewhat confusing to have a field name matching the declaring class name. This probably means that type and/or field names should be chosen more carefully. Understandability
AvoidFieldNameMatchingMethodName It can be confusing to have a field name with the same name as a method. While this is permitted, having information (field) and actions (method) is not clear naming. Developers versed in Smalltalk often prefer this approach as the methods denote accessor methods. Understandability
NoPackage Detects when a class or interface does not have a package definition. Understandability
PackageCase Detects when a package definition contains uppercase characters. Understandability
MisleadingVariableName Detects when a non-field has a name starting with ‘m_’. This usually denotes a field and could be confusing. Understandability
LocalVariableCouldBeFinal A local variable assigned only once can be declared final. Maintainability
MethodArgumentCouldBeFinal A method argument that is never re-assigned within the method can be declared final. Robustness
AvoidInstantiatingObjectsInLoops New objects created within loops should be checked to see if they can created outside them and reused. Resource Utilization
UseArrayListInsteadOfVector ArrayList is a much better Collection implementation than Vector if thread-safe operation is not required. Efficiency
SimplifyStartsWith 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. Accuracy
UseStringBufferForStringAppends The use of the ‘+=’ operator for appending strings causes the JVM to create and use an internal StringBuffer. If a non-trivial number of these concatenations are being used then the explicit use of a StringBuilder or threadsafe StringBuffer is recommended to avoid this. Resource Utilization
UseArraysAsList 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. It is faster than executing a loop to copy all the elements of the array one by one. Efficiency
AvoidArrayLoops Instead of manually copying data between two arrays, use the efficient System.arraycopy method instead. Efficiency
UnnecessaryWrapperObjectCreation Most wrapper classes provide static conversion methods that avoid the need to create intermediate objects just to create the primitive forms. Using these avoids the cost of creating objects that also need to begarbage-collected later. Resource Utilization
AddEmptyString The conversion of literals to strings by concatenating them with empty strings is inefficient. It is much better to use one of the type-specific toString() methods instead. Efficiency
RedundantFieldInitializer 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). Understandability
PrematureDeclaration Checks for variables that are defined before they might be used. A reference is deemed to be premature if it is created right before a block of code that doesn’t use it that also has the ability to return or throw an exception. Accuracy
AvoidCatchingThrowable Catching Throwable errors is not recommended since its scope is very broad. It includes runtime issues such as OutOfMemoryError that should be exposed and managed separately. Robustness
SignatureDeclareThrowsException Methods that declare the generic Exception as a possible throwable are not very helpful since their failure modes are unclear. Use a class derived from RuntimeException or a more specific checked exception. Analyzability
ExceptionAsFlowControl Using Exceptions as form of flow control is not recommended as they obscure true exceptions when debugging. Either add the necessary validation or use an alternate control structure. Analyzability
AvoidRethrowingException Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity. Robustness
DoNotExtendJavaLangError Errors are system exceptions. Do not extend them. Accuracy
DoNotThrowExceptionInFinally Throwing exceptions within a ‘finally’ block is confusing since they may mask other exceptions or code defects. Note: This is a PMD implementation of the Lint4j rule “A throw in a finally block” Robustness
AvoidThrowingNewInstanceOfSameException 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. Robustness
AvoidCatchingGenericException Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block Robustness
AvoidDuplicateLiterals Code containing duplicate String literals can usually be improved by declaring the String as a constant field. Understandability
StringToString Avoid calling toString() on objects already known to be string instances; this is unnecessary. Understandability
InefficientStringBuffering Avoid concatenating non-literals in a StringBuffer constructor or append() since intermediate buffers will need to be be created and destroyed by the JVM. Resource Utilization
UnnecessaryCaseChange Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals() Efficiency
UseStringBufferLength Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toString().equals(“”) or StringBuffer.toString().length() == … Accuracy
AppendCharacterWithChar Avoid concatenating characters as strings in StringBuffer/StringBuilder.append methods. Robustness
ConsecutiveAppendsShouldReuse Consecutively calls to StringBuffer/StringBuilder .append should reuse the target object. This can improve the performance. Efficiency
ConsecutiveLiteralAppends Consecutively calling StringBuffer/StringBuilder.append with String literals Efficiency
UseIndexOfChar Use String.indexOf(char) when checking for the index of a single character; it executes faster. Efficiency
InefficientEmptyStringCheck 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. Consider creating a static function that loops through a string, checking Character.isWhitespace() on each character and returning false if a non-whitespace character is found. Efficiency
InsufficientStringBufferDeclaration Failing to pre-size a StringBuffer or StringBuilder properly could cause it to re-size many times during runtime. This rule attempts to determine the total number the characters that are actually passed into StringBuffer.append(), but represents a best guess “worst case” scenario. An empty StringBuffer/StringBuilder constructor initializes the object to 16 characters. This default is assumed if the length of the constructor can not be determined. Robustness
UselessStringValueOf No need to call String.valueOf to append to a string; just use the valueOf() argument directly. Efficiency
UseEqualsToCompareStrings Using ‘==’ or ‘!=’ to compare strings only works if intern version is used on both sides. Use the equals() method instead. Accuracy
AvoidStringBufferField StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks if held within objects with long lifetimes. Resource Utilization
MethodReturnsInternalArray Exposing internal arrays to the caller violates object encapsulation since elements can be removed or replaced outside of the object that owns it. It is safer to return a copy of the array. Robustness
ArrayIsStoredDirectly Constructors and methods receiving arrays should clone objects and store the copy. This prevents future changes from the user from affecting the original array. Accuracy
UnnecessaryConversionTemporary Avoid the use temporary objects when converting primitives to Strings. Use the static conversion methods
on the wrapper classes instead.
UnnecessaryReturn Avoid the use of unnecessary return statements. Understandability
UnnecessaryFinalModifier When a class has the final modifier, all the methods are automatically final and do not need to be tagged as such. Maintainability
UselessOverridingMethod The overriding method merely calls the same method defined in a superclass. Understandability
UselessOperationOnImmutable 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. Therefore, ignoring the operation result is an error.
UnusedNullCheckInEquals After checking an object reference for null, you should invoke equals() on that object rather than passing it to another object’s equals() method. Accuracy
UselessQualifiedThis Look for qualified this usages in the same class. Understandability
UnusedPrivateField Detects when a private field is declared and/or assigned a value, but not used. Understandability
UnusedLocalVariable Detects when a local variable is declared and/or assigned, but not used. Understandability
UnusedPrivateMethod Unused Private Method detects when a private method is declared but is unused. Understandability
UnusedFormalParameter Avoid passing parameters to methods or constructors without actually referencing them in the method body. Maintainability
UnusedModifier Fields in interfaces are automatically public static final, and methods are public abstract. Classes or interfaces nested in an interface are automatically public and static (all nested interfaces are automatically static). For historical reasons, modifiers which are implied by the context are accepted by the compiler, but are superfluous. Understandability