Showing content from https://docs.pmd-code.org/latest/pmd_rules_java.html below:
Java Rules | PMD Source Code Analyzer
Index of all built-in rules available for Java
Table of Contents Best Practices
Rules which enforce generally accepted best practices.
- AbstractClassWithoutAbstractMethod: The abstract class does not contain any abstract methods. An abstract class suggests an incompletâ¦
- AccessorClassGeneration: Instantiation by way of private constructors from outside the constructorâs class often causes thâ¦
- AccessorMethodGeneration: When accessing private fields / methods from another class, the Java compiler will generate accesâ¦
- ArrayIsStoredDirectly: Constructors and methods receiving arrays should clone objects and store the copy. This prevents â¦
- AvoidMessageDigestField: Declaring a MessageDigest instance as a field make this instance directly available to multiple tâ¦
- AvoidPrintStackTrace: Avoid printStackTrace(); use a logger call instead.
- AvoidReassigningCatchVariables: Reassigning exception variables caught in a catch statement should be avoided because of: 1) If iâ¦
- AvoidReassigningLoopVariables: Reassigning loop variables can lead to hard-to-find bugs. Prevent or limit how these variables caâ¦
- AvoidReassigningParameters: Reassigning values to incoming parameters of a method or constructor is not recommended, as this â¦
- AvoidStringBufferField: StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks ifâ¦
- AvoidUsingHardCodedIP: Application with hard-coded IP addresses can become impossible to deploy in some cases. Externaliâ¦
- CheckResultSet: Always check the return values of navigation methods (next, previous, first, last) of a ResultSetâ¦
- ConstantsInInterface: Using constants in interfaces is a bad practice. Interfaces define types, constants are implementâ¦
- DefaultLabelNotLastInSwitch: By convention, the default label should be the last label in a switch statement or switch expressâ¦
- DefaultLabelNotLastInSwitchStmt: Deprecated The rule has been renamed. Use instead DefaultLabelNotLastInSwitch.
- DoubleBraceInitialization: Double brace initialisation is a pattern to initialise eg collections concisely. But it implicitlâ¦
- ExhaustiveSwitchHasDefault: When switching over an enum or sealed class, the compiler will ensure that all possible cases areâ¦
- ForLoopCanBeForeach: Reports loops that can be safely replaced with the foreach syntax. The rule considers loops over â¦
- ForLoopVariableCount: Having a lot of control variables in a âforâ loop makes it harder to see what range of values theâ¦
- GuardLogStatement: Whenever using a log level, one should check if it is actually enabled, or otherwise skip the assâ¦
- ImplicitFunctionalInterface: Reports functional interfaces that were not explicitly declared as such with the annoâ¦
- JUnit4SuitesShouldUseSuiteAnnotation: In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicated thrâ¦
- JUnit4TestShouldUseAfterAnnotation: Deprecated The rule has been renamed. Use instead UnitTestShouldUseAfterAnnotation.
- JUnit4TestShouldUseBeforeAnnotation: Deprecated The rule has been renamed. Use instead UnitTestShouldUseBeforeAnnotation.
- JUnit4TestShouldUseTestAnnotation: Deprecated The rule has been renamed. Use instead UnitTestShouldUseTestAnnotation.
- JUnit5TestShouldBePackagePrivate: Reports JUnit 5 test classes and methods that are not package-private. Contrary to JUnit 4 tests,â¦
- JUnitAssertionsShouldIncludeMessage: Deprecated The rule has been renamed. Use instead UnitTestAssertionsShouldIncludeMessage.
- JUnitTestContainsTooManyAsserts: Deprecated The rule has been renamed. Use instead UnitTestContainsTooManyAsserts.
- JUnitTestsShouldIncludeAssert: Deprecated The rule has been renamed. Use instead UnitTestShouldIncludeAssert.
- JUnitUseExpected: In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions.
- LiteralsFirstInComparisons: Position literals first in all String comparisons, if the second argument is null then NullPointeâ¦
- LooseCoupling: Excessive coupling to implementation types (e.g., âHashSetâ) limits your ability to use alternateâ¦
- MethodReturnsInternalArray: Exposing internal arrays to the caller violates object encapsulation since elements can be removeâ¦
- MissingOverride: Annotating overridden methods with @Override ensures at compile time that the method â¦
- NonExhaustiveSwitch: Switch statements should be exhaustive, to make their control flow easier to follow. â¦
- OneDeclarationPerLine: Java allows the use of several variables declaration of the same type on one line. However, it caâ¦
- PreserveStackTrace: Reports exceptions that are thrown from within a catch block, yet donât refer to the exception paâ¦
- PrimitiveWrapperInstantiation: Reports usages of primitive wrapper constructors. They are deprecated since Java 9 anâ¦
- ReplaceEnumerationWithIterator: Consider replacing Enumeration usages with the newer java.util.Iterator
- ReplaceHashtableWithMap: Consider replacing Hashtable usage with the newer java.util.Map if thread safety is not required.
- ReplaceVectorWithList: Consider replacing Vector usages with the newer java.util.ArrayList if expensive thread-safe operâ¦
- SimplifiableTestAssertion: Reports test assertions that may be simplified using a more specific assertion methodâ¦
- SwitchStmtsShouldHaveDefault: Deprecated The rule has been renamed. Use instead NonExhaustiveSwitch.
- SystemPrintln: References to System.(out|err).print are usually intended for debugging purposes and can remain â¦
- UnitTestAssertionsShouldIncludeMessage: Unit assertions should include an informative message - i.e., use the three-argument version of ââ¦
- UnitTestContainsTooManyAsserts: Unit tests should not contain too many asserts. Many asserts are indicative of a complex test, foâ¦
- UnitTestShouldIncludeAssert: Unit tests should include at least one assertion. This makes the tests more robust, and using assâ¦
- UnitTestShouldUseAfterAnnotation: This rule detects methods called âtearDown()â that are not properly annotated as a cleanup methodâ¦
- UnitTestShouldUseBeforeAnnotation: This rule detects methods called âsetUp()â that are not properly annotated as a setup method. Thiâ¦
- UnitTestShouldUseTestAnnotation: The rule will detect any test method starting with "test" that is not properly annotated, and wilâ¦
- UnnecessaryVarargsArrayCreation: Reports explicit array creation when a varargs is expected. For instance: â¦
- UnnecessaryWarningSuppression: This rule reports suppression comments and annotations that did not suppress any PMD violation. â¦
- UnusedAssignment: Reports assignments to variables that are never used before the variable is overwritten, â¦
- UnusedFormalParameter: Reports parameters of methods and constructors that are not referenced them in the method body. Pâ¦
- UnusedLocalVariable: Detects when a local variable is declared and/or assigned, but not used. Variables whose name staâ¦
- UnusedPrivateField: Detects when a private field is declared and/or assigned a value, but not used. Since PMD 6.50.0 â¦
- UnusedPrivateMethod: Unused Private Method detects when a private method is declared but is unused.
- UseCollectionIsEmpty: The isEmpty() method on java.util.Collection is provided to determine if a collection has any eleâ¦
- UseEnumCollections: Wherever possible, use âEnumSetâ or âEnumMapâ instead of âHashSetâ and âHashMapâ when the keys â¦
- UseStandardCharsets: Starting with Java 7, StandardCharsets provides constants for common Charset objects, such as UTFâ¦
- UseTryWithResources: Java 7 introduced the try-with-resources statement. This statement ensures that each resource is â¦
- UseVarargs: Java 5 introduced the varargs parameter declaration for methods and constructors. This syntactic â¦
- WhileLoopWithLiteralBoolean: âdo {} while (true);â requires reading the end of the statement before it is apparent that it looâ¦
Code Style
Rules which enforce a specific coding style.
- AtLeastOneConstructor: Each non-static class should declare at least one constructor. Classes with solely static membersâ¦
- AvoidDollarSigns: Avoid using dollar signs in variable/method/class/interface names.
- AvoidProtectedFieldInFinalClass: Do not use protected fields in final classes since they cannot be subclassed. Clarify your intentâ¦
- AvoidProtectedMethodInFinalClassNotExtending: Do not use protected methods in most final classes since they cannot be subclassed. This should oâ¦
- AvoidUsingNativeCode: Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portabilitâ¦
- BooleanGetMethodName: Methods that return boolean or Boolean results should be named as predicate statements to denote â¦
- CallSuperInConstructor: It is a good practice to call super() in a constructor. If super() is not called but another consâ¦
- ClassNamingConventions: Configurable naming conventions for type declarations. This rule reports type declaraâ¦
- CommentDefaultAccessModifier: To avoid mistakes if we want that an Annotation, Class, Enum, Method, Constructor or Field have aâ¦
- ConfusingTernary: Avoid negation within an "if" expression with an "else" clause. For example, rephrase: âif (x !=â¦
- ControlStatementBraces: Enforce a policy for braces on control statements. It is recommended to use braces on âif ⦠elsâ¦
- EmptyControlStatement: Reports control statements whose body is empty, as well as empty initializers. The châ¦
- EmptyMethodInAbstractClassShouldBeAbstract: Empty or auto-generated methods in an abstract class should be tagged as abstract. This helps to â¦
- ExtendsObject: No need to explicitly extend Object.
- FieldDeclarationsShouldBeAtStartOfClass: Fields should be declared at the top of the class, before any method declarations, constructors, â¦
- FieldNamingConventions: Configurable naming conventions for field declarations. This rule reports variable declarations â¦
- FinalParameterInAbstractMethod: Declaring a method parameter as final for an interface method is useless because the implementatiâ¦
- ForLoopShouldBeWhileLoop: Some for loops can be simplified to while loops, this makes them more concise.
- FormalParameterNamingConventions: Configurable naming conventions for formal parameters of methods and lambdas. This ruâ¦
- GenericsNaming: Names for references to generic values should be limited to a single uppercase letter.
- IdenticalCatchBranches: Identical âcatchâ branches use up vertical space and increase the complexity of code without â¦
- LambdaCanBeMethodReference: This rule reports lambda expressions that can be written more succinctly as a method reference. Tâ¦
- LinguisticNaming: This rule finds Linguistic Naming Antipatterns. It checks for fields, that are named, as if they â¦
- LocalHomeNamingConvention: The Local Home interface of a Session EJB should be suffixed by âLocalHomeâ.
- LocalInterfaceSessionNamingConvention: The Local Interface of a Session EJB should be suffixed by âLocalâ.
- LocalVariableCouldBeFinal: A local variable assigned only once can be declared final.
- LocalVariableNamingConventions: Configurable naming conventions for local variable declarations and other locally-scoped â¦
- LongVariable: Fields, formal arguments, or local variable names that are too long can make the code difficult tâ¦
- MDBAndSessionBeanNamingConvention: The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by âBeanâ.
- MethodArgumentCouldBeFinal: Reports method and constructor parameters that can be made final because they are never reassigneâ¦
- MethodNamingConventions: Configurable naming conventions for method declarations. This rule reports method decâ¦
- NoPackage: Detects when a class, interface, enum or annotation does not have a package definition.
- OnlyOneReturn: A method should have only one exit point, and that should be the last statement in the method.
- PackageCase: Detects when a package definition contains uppercase characters.
- PrematureDeclaration: Checks for variables that are defined before they might be used. A declaration is deemed to be prâ¦
- RemoteInterfaceNamingConvention: Remote Interface of a Session EJB should not have a suffix.
- RemoteSessionInterfaceNamingConvention: A Remote Home interface type of a Session EJB should be suffixed by âHomeâ.
- ShortClassName: Short Classnames with fewer than e.g. five characters are not recommended.
- ShortMethodName: Method names that are very short are not helpful to the reader.
- ShortVariable: Fields, local variables, enum constant names or parameter names that are very short are not helpfâ¦
- TooManyStaticImports: If you overuse the static import feature, it can make your program unreadable and unmaintainable,â¦
- UnnecessaryAnnotationValueElement: Avoid the use of value in annotations when itâs the only element.
- UnnecessaryBoxing: Reports explicit boxing and unboxing conversions that may safely be removed, either bâ¦
- UnnecessaryCast: Detects casts which could be removed as the operand of the cast is already suitable for the conteâ¦
- UnnecessaryConstructor: This rule detects when a constructor is not necessary; i.e., when there is only one constructor aâ¦
- UnnecessaryFullyQualifiedName: Import statements allow the use of non-fully qualified names. The use of a fully qualified name â¦
- UnnecessaryImport: Reports import statements that can be removed. They are either unused, duplicated, orâ¦
- UnnecessaryLocalBeforeReturn: Avoid the creation of unnecessary local variables
- UnnecessaryModifier: Fields in interfaces and annotations are automatically âpublic static finalâ, and methods are âpuâ¦
- UnnecessaryReturn: Avoid the use of unnecessary return statements. A return is unnecessary when no instructions follâ¦
- UnnecessarySemicolon: Reports unnecessary semicolons (so called "empty statements" and "empty declarations"). â¦
- UseDiamondOperator: In some cases, explicit type arguments in a constructor call for a generic type may be replaced bâ¦
- UseExplicitTypes: Java 10 introduced the âvarâ keyword. This reduces the amount of code written because java can inâ¦
- UselessParentheses: Parenthesized expressions are used to override the default operator precedence rulesâ¦.
- UselessQualifiedThis: Reports qualified this usages in the same class.
- UseShortArrayInitializer: When declaring and initializing array fields or variables, it is not necessary to explicitly creaâ¦
- UseUnderscoresInNumericLiterals: Since Java 1.7, numeric literals can use underscores to separate digits. This rule enforces that â¦
Design
Rules that help you discover design issues.
- AbstractClassWithoutAnyMethod: If an abstract class does not provide any methods, it may be acting as a simple data container thâ¦
- AvoidCatchingGenericException: Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in trâ¦
- AvoidDeeplyNestedIfStmts: Avoid creating deeply nested if-then statements since they are harder to read and error-prone to â¦
- AvoidRethrowingException: Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity.
- AvoidThrowingNewInstanceOfSameException: Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same typâ¦
- AvoidThrowingNullPointerException: Avoid throwing NullPointerExceptions manually. These are confusing because most people will assumâ¦
- AvoidThrowingRawExceptionTypes: Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exceâ¦
- AvoidUncheckedExceptionsInSignatures: Reports unchecked exceptions in the âthrowsâ clause of a method or constructor. Java doesnât forcâ¦
- ClassWithOnlyPrivateConstructorsShouldBeFinal: Reports classes that may be made final because they cannot be extended from outside their compilaâ¦
- CognitiveComplexity: Methods that are highly complex are difficult to read and more costly to maintain. If you includeâ¦
- CollapsibleIfStatements: Reports nested âifâ statements that can be merged together by joining their conditions with a booâ¦
- CouplingBetweenObjects: This rule counts the number of unique attributes, local variables, and return types within an objâ¦
- CyclomaticComplexity: The complexity of methods directly affects maintenance costs and readability. Concentrating too mâ¦
- DataClass: Data Classes are simple data holders, which reveal most of their state, and without complex functâ¦
- DoNotExtendJavaLangError: Errors are system exceptions. Do not extend them.
- ExceptionAsFlowControl: This rule reports exceptions thrown and caught in an enclosing try statement. This use of exceptiâ¦
- ExcessiveImports: A high number of imports can indicate a high degree of coupling within an object. This rule countâ¦
- ExcessiveParameterList: Methods with numerous parameters are a challenge to maintain, especially if most of them share thâ¦
- ExcessivePublicCount: Classes with large numbers of public methods and attributes require disproportionate testing effoâ¦
- FinalFieldCouldBeStatic: If a final field is assigned to a compile-time constant, it could be made static, thus saving oveâ¦
- GodClass: The God Class rule detects the God Class design flaw using metrics. God classes do too many thingâ¦
- ImmutableField: Reports non-final fields whose value never changes once object initialization ends, and hence mayâ¦
- InvalidJavaBean: Identifies beans, that donât follow the [JavaBeans API specification](https://download.oracle.comâ¦
- LawOfDemeter: The law of Demeter is a simple rule that says "only talk to friends". It forbids fetching data frâ¦
- LogicInversion: Use opposite operator instead of negating the whole expression with a logic complement operator.
- LoosePackageCoupling: Avoid using classes from the configured package hierarchy outside of the package hierarchy, excepâ¦
- MutableStaticState: Non-private static fields should be made constants (or immutable references) by declaring them fiâ¦
- NcssCount: This rule uses the NCSS (Non-Commenting Source Statements) metric to determine the number of lineâ¦
- NPathComplexity: The NPath complexity of a method is the number of acyclic execution paths through that method. Whâ¦
- SignatureDeclareThrowsException: A method/constructor shouldnât explicitly throw the generic java.lang.Exception, since it is unclâ¦
- SimplifiedTernary: Reports ternary expression with the form âcondition ? literalBoolean : fooâ or âcondition ? foo :â¦
- SimplifyBooleanExpressions: Avoid unnecessary comparisons in boolean expressions, they serve no purpose and impacts readability.
- SimplifyBooleanReturns: Avoid unnecessary if-then-else statements when returning a boolean. The result of the conditionalâ¦
- SimplifyConditional: No need to check for null before an instanceof; the instanceof keyword returns false when given aâ¦
- SingularField: Reports fields which may be converted to a local variable. This is so because in every method wheâ¦
- SwitchDensity: A high ratio of statements to labels in a switch statement implies that the switch statement is oâ¦
- TooManyFields: Classes that have too many fields can become unwieldy and could be redesigned to have fewer fieldâ¦
- TooManyMethods: A class with too many methods is probably a good suspect for refactoring, in order to reduce its â¦
- UselessOverridingMethod: The overriding method merely calls the same method defined in a superclass.
- UseObjectForClearerAPI: When you write a public method, you should be thinking in terms of an API. If your method is publâ¦
- UseUtilityClass: For classes that only have static methods, consider making them utility classes. Note that this dâ¦
Documentation
Rules that are related to code documentation.
- CommentContent: A rule for the politically correct⦠we donât want to offend anyone.
- CommentRequired: Denotes whether javadoc (formal) comments are required (or unwanted) for specific language elements.
- CommentSize: Determines whether the dimensions of non-header comments found are within the specified limits.
- UncommentedEmptyConstructor: Uncommented Empty Constructor finds instances where a constructor does not contain statements, buâ¦
- UncommentedEmptyMethodBody: Uncommented Empty Method Body finds instances where a method body does not contain statements, buâ¦
Error Prone
Rules to detect constructs that are either broken, extremely confusing or prone to runtime errors.
- AssignmentInOperand: Avoid assignments in operands; this can make code more complicated and harder to read.
- AssignmentToNonFinalStatic: Identifies a possible unsafe usage of a static field.
- AvoidAccessibilityAlteration: Methods such as âgetDeclaredConstructors()â, âgetDeclaredMethods()â, and âgetDeclaredFields()â alâ¦
- AvoidAssertAsIdentifier: Use of the term âassertâ will conflict with newer versions of Java since it is a reserved word. Sâ¦
- AvoidBranchingStatementAsLastInLoop: Using a branching statement as the last part of a loop may be a bug, and/or is confusing. Ensure â¦
- AvoidCallingFinalize: The method Object.finalize() is called by the garbage collector on an object when garbage collectâ¦
- AvoidCatchingNPE: Code should never throw NullPointerExceptions under normal circumstances. A catch block may hideâ¦
- AvoidCatchingThrowable: Catching Throwable errors is not recommended since its scope is very broad. It includes runtime iâ¦
- AvoidDecimalLiteralsInBigDecimalConstructor: One might assume that the result of "new BigDecimal(0.1)" is exactly equal to 0.1, but it is actuâ¦
- AvoidDuplicateLiterals: Code containing duplicate String literals can usually be improved by declaring the String as a coâ¦
- AvoidEnumAsIdentifier: Use of the term âenumâ will conflict with newer versions of Java since it is a reserved word. Sinâ¦
- AvoidFieldNameMatchingMethodName: It can be confusing to have a field name with the same name as a method. While this is permitted,â¦
- AvoidFieldNameMatchingTypeName: It is somewhat confusing to have a field name matching the declaring type name. This probably meaâ¦
- AvoidInstanceofChecksInCatchClause: Each caught exception type should be handled in its own catch clause.
- AvoidLiteralsInIfCondition: Avoid using hard-coded literals in conditional statements. By declaring them as static variables â¦
- AvoidLosingExceptionInformation: Statements in a catch block that invoke accessors on the exception without using the information â¦
- AvoidMultipleUnaryOperators: The use of multiple unary operators may be problematic, and/or confusing. Ensure that the intendeâ¦
- AvoidUsingOctalValues: Integer literals should not start with zero since this denotes that the rest of literal will be iâ¦
- BrokenNullCheck: The null check is broken since it will throw a NullPointerException itself. It is likely that youâ¦
- CallSuperFirst: Super should be called at the start of the method
- CallSuperLast: Super should be called at the end of the method
- CheckSkipResult: The skip() method may skip a smaller number of bytes than requested. Check the returned value to â¦
- ClassCastExceptionWithToArray: When deriving an array of a specific class from your Collection, one should provide an array of tâ¦
- CloneMethodMustBePublic: The java manual says "By convention, classes that implement this interface should override Objectâ¦
- CloneMethodMustImplementCloneable: The method clone() should only be implemented if the class implements the Cloneable interface witâ¦
- CloneMethodReturnTypeMustMatchClassName: If a class implements âCloneableâ the return type of the method âclone()â must be the class nameâ¦.
- CloseResource: Ensure that resources (like âjava.sql.Connectionâ, âjava.sql.Statementâ, and âjava.sql.ResultSetââ¦
- CompareObjectsWithEquals: Use âequals()â to compare object references; avoid comparing them with â==â. Since comparing objeâ¦
- ComparisonWithNaN: Reports comparisons with double and float âNaNâ (Not-a-Number) values. These are [speâ¦
- ConfusingArgumentToVarargsMethod: Reports a confusing argument passed to a varargs method. This can occur when an arrayâ¦
- ConstructorCallsOverridableMethod: Reports calls to overridable methods on âthisâ during object initialization. These are invoked onâ¦
- DetachedTestCase: The method appears to be a test case since it has public or default visibility, non-static accessâ¦
- DoNotCallGarbageCollectionExplicitly: Calls to âSystem.gc()â, âRuntime.getRuntime().gc()â, and âSystem.runFinalization()â are not advisâ¦
- DoNotExtendJavaLangThrowable: Extend Exception or RuntimeException instead of Throwable.
- DoNotHardCodeSDCard: Use Environment.getExternalStorageDirectory() instead of "/sdcard"
- DoNotTerminateVM: Web applications should not call âSystem.exit()â, since only the web container or the applicationâ¦
- DoNotThrowExceptionInFinally: Throwing exceptions within a âfinallyâ block is confusing since they may mask other exceptions orâ¦
- DontImportSun: Avoid importing anything from the âsun.â packages. These packages are not portable and are likelyâ¦
- DontUseFloatTypeForLoopIndices: Donât use floating point for loop indices. If you must use floating point, use double unless youââ¦
- EmptyCatchBlock: Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circâ¦
- EmptyFinalizer: Empty finalize methods serve no purpose and should be removed. Note that Oracle has declared Objeâ¦
- EqualsNull: Tests for null should not use the equals() method. The â==â operator should be used instead.
- FinalizeDoesNotCallSuperFinalize: If the finalize() is implemented, its last action should be to call super.finalize. Note that Oraâ¦
- FinalizeOnlyCallsSuperFinalize: If the finalize() is implemented, it should do something besides just calling super.finalize(). Nâ¦
- FinalizeOverloaded: Methods named finalize() should not have parameters. It is confusing and most likely an attempt â¦
- FinalizeShouldBeProtected: When overriding the finalize(), the new method should be set as protected. If made public, otherâ¦
- IdempotentOperations: Avoid idempotent operations - they have no effect.
- ImplicitSwitchFallThrough: Switch statements without break or return statements for each case option may indicate problematiâ¦
- InstantiationToGetClass: Avoid instantiating an object just to call getClass() on it; use the .class public member instead.
- InvalidLogMessageFormat: Check for messages in slf4j and log4j2 (since 6.19.0) loggers with non matching number of argumenâ¦
- JumbledIncrementer: Avoid jumbled loop incrementers - itâs usually a mistake, and is confusing even if intentional.
- JUnitSpelling: In JUnit 3, the setUp method is used to set up all data entities required in running tests. â¦
- JUnitStaticSuite: The suite() method in a JUnit test needs to be both public and static.
- MethodWithSameNameAsEnclosingClass: A method should not have the same name as its containing class. This would be confusing as it wouâ¦
- MisplacedNullCheck: The null check here is misplaced. If the variable is null a âNullPointerExceptionâ will be thrownâ¦
- MissingSerialVersionUID: Serializable classes should provide a serialVersionUID field. The serialVersionUID field is also â¦
- MissingStaticMethodInNonInstantiatableClass: A class that has private constructors and does not have any static methods or fields cannot be usâ¦
- MoreThanOneLogger: Normally only one logger is used in each class. This rule supports slf4j, log4j, Java Util Logginâ¦
- NonCaseLabelInSwitch: A non-case label (e.g. a named break/continue label) was present in a switch statement or switch â¦
- NonCaseLabelInSwitchStatement: Deprecated The rule has been renamed. Use instead NonCaseLabelInSwitch.
- NonSerializableClass: If a class is marked as âSerializableâ, then all fields need to be serializable as well. In orderâ¦
- NonStaticInitializer: A non-static initializer block will be called any time a constructor is invoked (just prior to inâ¦
- NullAssignment: Assigning a "null" to a variable (outside of its declaration) is usually bad form. Sometimes, thâ¦
- OverrideBothEqualsAndHashcode: Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or ovâ¦
- ProperCloneImplementation: Object clone() should be implemented with super.clone().
- ProperLogger: A logger should normally be defined private static final and be associated with the correct classâ¦
- ReplaceJavaUtilCalendar: The legacy java.util.Calendar API is error-prone, mutable, and not thread-safe. It has confusing â¦
- ReplaceJavaUtilDate: The legacy java.util.Date class is mutable, not thread-safe, and has a confusing API. Many of itsâ¦
- ReturnEmptyCollectionRatherThanNull: For any method that returns an collection (such as an array, Collection or Map), it is better to â¦
- ReturnFromFinallyBlock: Avoid returning from a finally block, this can discard exceptions.
- SimpleDateFormatNeedsLocale: Be sure to specify a Locale when creating SimpleDateFormat instances to ensure that locale-appropâ¦
- SingleMethodSingleton: Some classes contain overloaded getInstance. The problem with overloaded getInstance methods is tâ¦
- SingletonClassReturningNewInstance: A singleton class should only ever have one instance. Failure to check whether an insâ¦
- StaticEJBFieldShouldBeFinal: According to the J2EE specification, an EJB should not have any static fields with write access. â¦
- StringBufferInstantiationWithChar: Individual character values provided as initialization arguments will be converted into integersâ¦.
- SuspiciousEqualsMethodName: The method name and parameter number are suspiciously close to âObject.equalsâ, which can denote â¦
- SuspiciousHashcodeMethodName: The method name and return type are suspiciously close to hashCode(), which may denote an intentiâ¦
- SuspiciousOctalEscape: A suspicious octal escape sequence was found inside a String literal. The Java language specificaâ¦
- TestClassWithoutTestCases: Test classes typically end with the suffix "Test", "Tests" or "TestCase". Having a non-test classâ¦
- UnconditionalIfStatement: Do not use "if" statements whose conditionals are always true or always false.
- UnnecessaryBooleanAssertion: A JUnit test assertion with a boolean literal is unnecessary since it always will evaluate to theâ¦
- UnnecessaryCaseChange: Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()
- UnnecessaryConversionTemporary: Avoid the use temporary objects when converting primitives to Strings. Use the static conversion â¦
- UnusedNullCheckInEquals: After checking an object reference for null, you should invoke equals() on that object rather thaâ¦
- UseCorrectExceptionLogging: To make sure the full stacktrace is printed out, use the logging statement with two arguments: a â¦
- UseEqualsToCompareStrings: Using â==â or â!=â to compare strings is only reliable if the interned string (âString#intern()â)â¦
- UselessOperationOnImmutable: An operation on an immutable object will not change the object itself since the result of the opeâ¦
- UseLocaleWithCaseConversions: When doing âString::toLowerCase()/toUpperCase()â conversions, use an explicit locale argument to â¦
- UseProperClassLoader: In J2EE, the getClassLoader() method might not work as expected. Use Thread.currentThread().getCoâ¦
Multithreading
Rules that flag issues when dealing with multiple threads of execution.
- AvoidSynchronizedAtMethodLevel: Method-level synchronization will pin virtual threads and can cause performance problems. Additioâ¦
- AvoidSynchronizedStatement: Synchronization will pin virtual threads and can cause performance problems.
- AvoidThreadGroup: Avoid using java.lang.ThreadGroup; although it is intended to be used in a threaded environment iâ¦
- AvoidUsingVolatile: Use of the keyword âvolatileâ is generally used to fine tune a Java application, and therefore, râ¦
- DoNotUseThreads: The J2EE specification explicitly forbids the use of threads. Threads are resources, that should â¦
- DontCallThreadRun: Explicitly calling Thread.run() method will execute in the callerâs thread of control. Instead, â¦
- DoubleCheckedLocking: Partially created objects can be returned by the Double Checked Locking pattern when used in Javaâ¦
- NonThreadSafeSingleton: Non-thread safe singletons can result in bad state changes. Eliminate static singletons if possibâ¦
- UnsynchronizedStaticFormatter: Instances of âjava.text.Formatâ are generally not synchronized. Sun recommends using separate forâ¦
- UseConcurrentHashMap: Since Java5 brought a new implementation of the Map designed for multi-threaded access, you can pâ¦
- UseNotifyAllInsteadOfNotify: Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, thâ¦
Performance
Rules that flag suboptimal code.
- AddEmptyString: The conversion of literals to strings by concatenating them with empty strings is inefficient. Itâ¦
- AppendCharacterWithChar: Avoid concatenating characters as strings in StringBuffer/StringBuilder.append methods.
- AvoidArrayLoops: Instead of manually copying data between two arrays, use the more efficient âArrays.copyOfâ or âSâ¦
- AvoidCalendarDateCreation: Problem: âjava.util.Calendarâ is a heavyweight object and expensive to create. It should only be â¦
- AvoidFileStream: The FileInputStream and FileOutputStream classes contains a finalizer method which will cause garâ¦
- AvoidInstantiatingObjectsInLoops: New objects created within loops should be checked to see if they can created outside them and reâ¦
- BigIntegerInstantiation: Donât create instances of already existing BigInteger (âBigInteger.ZEROâ, âBigInteger.ONEâ), for â¦
- ConsecutiveAppendsShouldReuse: Consecutive calls to StringBuffer/StringBuilder .append should be chained, reusing the target objâ¦
- ConsecutiveLiteralAppends: Consecutively calling StringBuffer/StringBuilder.append(â¦) with literals should be avoided. Sinâ¦
- InefficientEmptyStringCheck: String.trim().length() == 0 (or String.trim().isEmpty() for the same reason) is an inefficient waâ¦
- InefficientStringBuffering: Avoid concatenating non-literals in a StringBuffer constructor or append() since intermediate bufâ¦
- InsufficientStringBufferDeclaration: Failing to pre-size a StringBuffer or StringBuilder properly could cause it to re-size many timesâ¦
- OptimizableToArrayCall: Calls to a collectionâs âtoArray(E[])â method should specify a target array of zero size. This alâ¦
- RedundantFieldInitializer: Java will initialize fields with known default values so any explicit initialization of those samâ¦
- StringInstantiation: Avoid instantiating String objects; this is usually unnecessary since they are immutable and can â¦
- StringToString: Avoid calling toString() on objects already known to be string instances; this is unnecessary.
- TooFewBranchesForASwitchStatement: Deprecated The rule has been renamed. Use instead TooFewBranchesForSwitch.
- TooFewBranchesForSwitch: Switch statements are intended to be used to support complex branching behaviour. Using a switch â¦
- UseArrayListInsteadOfVector: ArrayList is a much better Collection implementation than Vector if thread-safe operation is not â¦
- UseArraysAsList: The âjava.util.Arraysâ class has a âasList()â method that should be used when you want to create â¦
- UseIndexOfChar: Use String.indexOf(char) when checking for the index of a single character; it executes faster.
- UseIOStreamsWithApacheCommonsFileItem: Problem: Use of [FileItem.get()](https://javadoc.io/static/commons-fileupload/commons-fileupload/â¦
- UselessStringValueOf: No need to call String.valueOf to append to a string; just use the valueOf() argument directly.
- UseStringBufferForStringAppends: The use of the â+=â operator for appending strings causes the JVM to create and use an internal Sâ¦
- UseStringBufferLength: Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toStrinâ¦
Security
Rules that flag potential security flaws.
- HardCodedCryptoKey: Do not use hard coded values for cryptographic operations. Please store keys outside of source code.
- InsecureCryptoIv: Do not use hard coded initialization vector in cryptographic operations. Please use a randomly geâ¦
Additional rulesets
-
quickstart (rulesets/java/quickstart.xml
):
Quickstart configuration of PMD. Includes the rules that are most likely to apply everywhere.
It contains the following rules:
AbstractClassWithoutAnyMethod, AssignmentInOperand, AssignmentToNonFinalStatic, AvoidAccessibilityAlteration, AvoidBranchingStatementAsLastInLoop, AvoidCatchingThrowable, AvoidDecimalLiteralsInBigDecimalConstructor, AvoidDollarSigns, AvoidInstanceofChecksInCatchClause, AvoidMessageDigestField, AvoidMultipleUnaryOperators, AvoidProtectedFieldInFinalClass, AvoidProtectedMethodInFinalClassNotExtending, AvoidStringBufferField, AvoidThreadGroup, AvoidUsingHardCodedIP, AvoidUsingOctalValues, AvoidUsingVolatile, BigIntegerInstantiation, BrokenNullCheck, CheckResultSet, CheckSkipResult, ClassCastExceptionWithToArray, ClassNamingConventions, ClassWithOnlyPrivateConstructorsShouldBeFinal, CloneMethodMustBePublic, CloneMethodMustImplementCloneable, CloneMethodReturnTypeMustMatchClassName, CloseResource, CompareObjectsWithEquals, ComparisonWithNaN, ConstantsInInterface, ControlStatementBraces, DefaultLabelNotLastInSwitch, DoNotCallGarbageCollectionExplicitly, DoNotExtendJavaLangError, DoNotExtendJavaLangThrowable, DontCallThreadRun, DontUseFloatTypeForLoopIndices, DoubleBraceInitialization, DoubleCheckedLocking, EmptyCatchBlock, EmptyControlStatement, EmptyFinalizer, EqualsNull, ExtendsObject, FinalFieldCouldBeStatic, FinalParameterInAbstractMethod, ForLoopCanBeForeach, ForLoopShouldBeWhileLoop, FormalParameterNamingConventions, GenericsNaming, GuardLogStatement, IdempotentOperations, IdenticalCatchBranches, ImplicitSwitchFallThrough, InstantiationToGetClass, JumbledIncrementer, LambdaCanBeMethodReference, LiteralsFirstInComparisons, LocalVariableNamingConventions, LogicInversion, LooseCoupling, MethodNamingConventions, MisplacedNullCheck, MissingOverride, MissingStaticMethodInNonInstantiatableClass, NonCaseLabelInSwitch, NonExhaustiveSwitch, NonStaticInitializer, NonThreadSafeSingleton, NoPackage, OneDeclarationPerLine, OptimizableToArrayCall, OverrideBothEqualsAndHashcode, PackageCase, PreserveStackTrace, PrimitiveWrapperInstantiation, ProperCloneImplementation, ProperLogger, ReturnEmptyCollectionRatherThanNull, ReturnFromFinallyBlock, SimplifiableTestAssertion, SimplifiedTernary, SimplifyBooleanReturns, SimplifyConditional, SingleMethodSingleton, SingletonClassReturningNewInstance, SingularField, SuspiciousEqualsMethodName, SuspiciousHashcodeMethodName, SuspiciousOctalEscape, UncommentedEmptyConstructor, UncommentedEmptyMethodBody, UnconditionalIfStatement, UnnecessaryAnnotationValueElement, UnnecessaryConstructor, UnnecessaryConversionTemporary, UnnecessaryFullyQualifiedName, UnnecessaryImport, UnnecessaryLocalBeforeReturn, UnnecessaryModifier, UnnecessaryReturn, UnnecessarySemicolon, UnsynchronizedStaticFormatter, UnusedFormalParameter, UnusedLocalVariable, UnusedNullCheckInEquals, UnusedPrivateField, UnusedPrivateMethod, UseCollectionIsEmpty, UseEqualsToCompareStrings, UselessOperationOnImmutable, UselessOverridingMethod, UselessParentheses, UselessQualifiedThis, UseLocaleWithCaseConversions, UseNotifyAllInsteadOfNotify, UseStandardCharsets, UseUtilityClass
RetroSearch is an open source project built by @garambo
| Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4