Since: PMD 1.04
Priority: Medium (3)
Each non-static class should declare at least one constructor.Classes with solely static members are ignored, refer toUseUtilityClassRule to detect those.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.AtLeastOneConstructorRule
Example(s):
publicclassFoo{// missing constructorpublicvoiddoSomething(){...}publicvoiddoOtherThing{...}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoredAnnotations | lombok.Data , lombok.Value , lombok.Builder , lombok.NoArgsConstructor , lombok.RequiredArgsConstructor , lombok.AllArgsConstructor | Fully qualified names of the annotation types that should be ignored by this rule |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/AtLeastOneConstructor"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/AtLeastOneConstructor"><properties><propertyname="ignoredAnnotations"value="lombok.Data,lombok.Value,lombok.Builder,lombok.NoArgsConstructor,lombok.RequiredArgsConstructor,lombok.AllArgsConstructor"/></properties></rule>Since: PMD 1.5
Priority: Medium (3)
Avoid using dollar signs in variable/method/class/interface names.
This rule is defined by the following XPath expression:
//ClassDeclaration[contains(@SimpleName,'$')]|//EnumDeclaration[contains(@SimpleName,'$')]|//AnnotationTypeDeclaration[contains(@SimpleName,'$')]|//RecordDeclaration[contains(@SimpleName,'$')]|//VariableId[contains(@Name,'$')]|//MethodDeclaration[contains(@Name,'$')]Example(s):
publicclassFo$o{// not a recommended name}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/AvoidDollarSigns"/>Since: PMD 2.1
Priority: Medium (3)
Do not use protected fields in final classes since they cannot be subclassed.Clarify your intent by using private or package access modifiers instead.
This rule is defined by the following XPath expression:
//ClassDeclaration[@Final=true()]/ClassBody/FieldDeclaration[@Visibility="protected"]Example(s):
publicfinalclassBar{privateintx;protectedinty;// bar cannot be subclassed, so is y really private or package visible?Bar(){}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/AvoidProtectedFieldInFinalClass"/>Since: PMD 5.1
Priority: Medium (3)
Do not use protected methods in most final classes since they cannot be subclassed. This shouldonly be allowed in final classes that extend other classes with protected methods (whosevisibility cannot be reduced). Clarify your intent by using private or package access modifiers instead.
This rule is defined by the following XPath expression:
//ClassDeclaration[@Final=true()andnot(ExtendsList)]/ClassBody/MethodDeclaration[@Visibility="protected"and@Name!='finalize']Example(s):
publicfinalclassFoo{privateintbar(){}protectedintbaz(){}// Foo cannot be subclassed, and doesn't extend anything, so is baz() really private or package visible?}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/AvoidProtectedMethodInFinalClassNotExtending"/>Since: PMD 4.1
Priority: Medium High (2)
Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portabilityand increases the maintenance burden.
This rule is defined by the following XPath expression:
//MethodCall[TypeExpression/ClassType[pmd-java:typeIs('java.lang.System')]and@MethodName='loadLibrary']Example(s):
publicclassSomeJNIClass{publicSomeJNIClass(){System.loadLibrary("nativelib");}static{System.loadLibrary("nativelib");}publicvoidinvalidCallsInMethod()throwsSecurityException,NoSuchMethodException{System.loadLibrary("nativelib");}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/AvoidUsingNativeCode"/>Since: PMD 4.0
Priority: Medium Low (4)
Methods that return boolean or Boolean results should be named as predicate statements to denote this.I.e., ‘isReady()’, ‘hasValues()’, ‘canCommit()’, ‘willFail()’, etc. Avoid the use of the ‘get’ prefix for these methods.
This rule is defined by the following XPath expression:
//MethodDeclaration[starts-with(@Name,'get')][@Arity=0or$checkParameterizedMethods=true()][(PrimitiveType[@Kind='boolean']orClassType[pmd-java:typeIs('java.lang.Boolean')])and@Overridden=false()]Example(s):
publicbooleangetFoo();// badpublicBooleangetFoo();// badpublicbooleanisFoo();// okpublicBooleanisFoo();// okpublicbooleangetFoo(booleanbar);// ok, unless checkParameterizedMethods=trueThis rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| checkParameterizedMethods | false | Check parameterized methods |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/BooleanGetMethodName"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/BooleanGetMethodName"><properties><propertyname="checkParameterizedMethods"value="false"/></properties></rule>Since: PMD 3.0
Priority: Medium (3)
It is a good practice to call super() in a constructor. If super() is not called butanother constructor (such as an overloaded constructor) is called, this rule will not report it.
This rule is defined by the following XPath expression:
//ClassDeclaration[ExtendsList/*]/ClassBody/ConstructorDeclaration[not(Block/ExplicitConstructorInvocation)]Example(s):
publicclassFooextendsBar{publicFoo(){// call the constructor of Barsuper();}publicFoo(intcode){// do something with codethis();// no problem with this}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/CallSuperInConstructor"/>Since: PMD 1.2
Priority: High (1)
Configurable naming conventions for type declarations. This rule reportstype declarations which do not match the regex that applies to theirspecific kind (e.g. enum or interface). Each regex can be configured throughproperties.
By default, this rule uses the standard Java naming convention (Pascal case).
The rule can detect utility classes and enforce a different naming conventionon those. E.g. setting the propertyutilityClassPattern to[A-Z][a-zA-Z0-9]+(Utils?|Helper|Constants) reports any utility class, whose namedoes not end in "Util(s)", "Helper" or "Constants".
For this rule, a utility class is defined as: a concrete class that does notinherit from a super class or implement any interface and only has static fieldsor methods.
This rule detects test classes using the following convention: Test classes are top-level classes, thateither inherit from JUnit 3 TestCase or have at least one method annotated with the Test annotations fromJUnit4/5 or TestNG.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.ClassNamingConventionsRule
Example(s):
// This is Pascal case, the recommended naming convention in Java// Note that the default values of this rule don't allow underscores// or accented characters in type namespublicclassFooBar{}// You may want abstract classes to be named 'AbstractXXX',// in which case you can customize the regex for abstract// classes to 'Abstract[A-Z]\w+'publicabstractclassThing{}// This class doesn't respect the convention, and will be flaggedpublicclassÉléphant{}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| classPattern | [A-Z][a-zA-Z0-9]* | Regex which applies to concrete class names |
| abstractClassPattern | [A-Z][a-zA-Z0-9]* | Regex which applies to abstract class names |
| interfacePattern | [A-Z][a-zA-Z0-9]* | Regex which applies to interface names |
| enumPattern | [A-Z][a-zA-Z0-9]* | Regex which applies to enum names |
| annotationPattern | [A-Z][a-zA-Z0-9]* | Regex which applies to annotation names |
| utilityClassPattern | [A-Z][a-zA-Z0-9]* | Regex which applies to utility class names |
| testClassPattern | ^Test.*$|^[A-Z][a-zA-Z0-9]*Test(s|Case)?$ | Regex which applies to test class names. Since PMD 6.52.0. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/ClassNamingConventions"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/ClassNamingConventions"><properties><propertyname="classPattern"value="[A-Z][a-zA-Z0-9]*"/><propertyname="abstractClassPattern"value="[A-Z][a-zA-Z0-9]*"/><propertyname="interfacePattern"value="[A-Z][a-zA-Z0-9]*"/><propertyname="enumPattern"value="[A-Z][a-zA-Z0-9]*"/><propertyname="annotationPattern"value="[A-Z][a-zA-Z0-9]*"/><propertyname="utilityClassPattern"value="[A-Z][a-zA-Z0-9]*"/><propertyname="testClassPattern"value="^Test.*$|^[A-Z][a-zA-Z0-9]*Test(s|Case)?$"/></properties></rule>Since: PMD 5.4.0
Priority: Medium (3)
To avoid mistakes if we want that an Annotation, Class, Enum, Method, Constructor or Field have a default access modifierwe must add a comment at the beginning of its declaration.By default, the comment must be/* default */ or/* package */, if you want another, you have to provide a regular expression.
This rule ignores by default all cases that have a@VisibleForTesting annotation or any JUnit5/TestNG annotation. Use theproperty "ignoredAnnotations" to customize the recognized annotations.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.CommentDefaultAccessModifierRule
Example(s):
publicclassFoo{finalStringstringValue="some string";StringgetString(){returnstringValue;}classNestedFoo{}}// should bepublicclassFoo{/* default */finalStringstringValue="some string";/* default */StringgetString(){returnstringValue;}/* default */classNestedFoo{}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoredAnnotations | android.support.annotation.VisibleForTesting , co.elastic.clients.util.VisibleForTesting , com.google.common.annotations.VisibleForTesting , org.junit.jupiter.api.AfterAll , org.junit.jupiter.api.AfterEach , org.junit.jupiter.api.BeforeAll , org.junit.jupiter.api.BeforeEach , org.junit.jupiter.api.RepeatedTest , org.junit.jupiter.api.Test , org.junit.jupiter.api.TestFactory , org.junit.jupiter.api.TestTemplate , org.junit.jupiter.api.extension.RegisterExtension , org.junit.jupiter.params.ParameterizedTest , org.testng.annotations.AfterClass , org.testng.annotations.AfterGroups , org.testng.annotations.AfterMethod , org.testng.annotations.AfterSuite , org.testng.annotations.AfterTest , org.testng.annotations.BeforeClass , org.testng.annotations.BeforeGroups , org.testng.annotations.BeforeMethod , org.testng.annotations.BeforeSuite , org.testng.annotations.BeforeTest , org.testng.annotations.Test | Fully qualified names of the annotation types that should be ignored by this rule |
| regex | \/\*\s*(default|package)\s*\*\/ | Regular expression |
| checkTopLevelTypes | false | Check for default access modifier in top-level classes, annotations, and enums |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/CommentDefaultAccessModifier"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/CommentDefaultAccessModifier"><properties><propertyname="ignoredAnnotations"value="android.support.annotation.VisibleForTesting,co.elastic.clients.util.VisibleForTesting,com.google.common.annotations.VisibleForTesting,org.junit.jupiter.api.AfterAll,org.junit.jupiter.api.AfterEach,org.junit.jupiter.api.BeforeAll,org.junit.jupiter.api.BeforeEach,org.junit.jupiter.api.RepeatedTest,org.junit.jupiter.api.Test,org.junit.jupiter.api.TestFactory,org.junit.jupiter.api.TestTemplate,org.junit.jupiter.api.extension.RegisterExtension,org.junit.jupiter.params.ParameterizedTest,org.testng.annotations.AfterClass,org.testng.annotations.AfterGroups,org.testng.annotations.AfterMethod,org.testng.annotations.AfterSuite,org.testng.annotations.AfterTest,org.testng.annotations.BeforeClass,org.testng.annotations.BeforeGroups,org.testng.annotations.BeforeMethod,org.testng.annotations.BeforeSuite,org.testng.annotations.BeforeTest,org.testng.annotations.Test"/><propertyname="regex"value="\/\*\s*(default|package)\s*\*\/"/><propertyname="checkTopLevelTypes"value="false"/></properties></rule>Since: PMD 1.9
Priority: Medium (3)
Avoid negation within an "if" expression with an "else" clause. For example, rephrase:if (x != y) diff(); else same(); as:if (x == y) same(); else diff();.
Most "if (x != y)" cases without an "else" are often return cases, so consistent use of thisrule makes the code easier to read. Also, this resolves trivial ordering problems, suchas "does the error case go first?" or "does the common case go first?".
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.ConfusingTernaryRule
Example(s):
booleanbar(intx,inty){return(x!=y)?diff:same;}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoreElseIf | false | Ignore conditions with an else-if case |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/ConfusingTernary"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/ConfusingTernary"><properties><propertyname="ignoreElseIf"value="false"/></properties></rule>Since: PMD 6.2.0
Priority: Medium (3)
Enforce a policy for braces on control statements. It is recommended to use braces on ‘if … else’statements and loop statements, even if they are optional. This usually makes the code clearer, andhelps prepare the future when you need to add another statement. That said, this rule lets you controlwhich statements are required to have braces via properties.
From 6.2.0 on, this rule supersedes WhileLoopMustUseBraces, ForLoopMustUseBraces, IfStmtMustUseBraces,and IfElseStmtMustUseBraces.
This rule is defined by the following XPath expression:
//WhileStatement[$checkWhileStmtandnot(Block)andnot($allowEmptyLoopandEmptyStatement)]|//ForStatement[$checkForStmtandnot(Block)andnot($allowEmptyLoopandEmptyStatement)]|//ForeachStatement[$checkForStmtandnot(Block)andnot($allowEmptyLoopandEmptyStatement)]|//DoStatement[$checkDoWhileStmtandnot(Block)andnot($allowEmptyLoopandEmptyStatement)]|(: The violation is reported on the sub statement -- not the if statement :)//IfStatement[$checkIfElseStmt]/*[position()>1andnot(self::Blockorself::IfStatement)][$checkSingleIfStmt(: Inside this (...) is the definition of a "single if statement" :)ornot(parent::*/@Else=false()(: No else stmt :)(: Not the last branch of an 'if ... else if' chain :)andnot(parent::IfStatement[parent::IfStatement]))]|(: Reports case labels if one of their subordinate statements is not braced :)//SwitchFallthroughBranch[$checkCaseStmt][count(*)>1and(count(*)>2ornot(child::*[2]/self::Block))]Example(s):
while(true)// not recommendedx++;while(true){// preferred approachx++;}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| checkIfElseStmt | true | Require that ‘if … else’ statements use braces |
| checkSingleIfStmt | true | Require that ‘if’ statements with a single branch use braces |
| checkWhileStmt | true | Require that ‘while’ loops use braces |
| checkForStmt | true | Require that ‘for’ loops should use braces |
| checkDoWhileStmt | true | Require that ‘do … while’ loops use braces |
| checkCaseStmt | false | Require that cases of a switch have braces |
| allowEmptyLoop | false | Allow loops with an empty statement, e.g. ‘while(true);’ |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/ControlStatementBraces"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/ControlStatementBraces"><properties><propertyname="checkIfElseStmt"value="true"/><propertyname="checkSingleIfStmt"value="true"/><propertyname="checkWhileStmt"value="true"/><propertyname="checkForStmt"value="true"/><propertyname="checkDoWhileStmt"value="true"/><propertyname="checkCaseStmt"value="false"/><propertyname="allowEmptyLoop"value="false"/></properties></rule>Since: PMD 6.46.0
Priority: Medium (3)
Reports control statements whose body is empty, as well as empty initializers.
The checked code constructs are the following:
try statementsfinally clauses oftry statementsswitch statementssynchronized statementsif statementswhile,for,do .. whileThis rule replaces the rules EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, and EmptyWhileStmt.
Notice thatEmptyCatchBlock is still an independent rule.
EmptyStatementNotInLoop is replaced byUnnecessarySemicolon.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.EmptyControlStatementRule
Example(s):
classFoo{{if(true);// empty if statementif(true){// empty as well}}{}// empty initializer}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| allowCommentedBlocks | false | Option for allowing empty but commented blocks. This is useful where a developer wants to have the code structure and explain why a condition does not require logic or to hold TODO comments for future work. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/EmptyControlStatement"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/EmptyControlStatement"><properties><propertyname="allowCommentedBlocks"value="false"/></properties></rule>Since: PMD 4.1
Priority: High (1)
Empty or auto-generated methods in an abstract class should be tagged as abstract. This helps to remove their inappropriateusage by developers who should be implementing their own versions in the concrete subclasses.
This rule is defined by the following XPath expression:
//ClassDeclaration[@RegularClass=true()andpmd-java:modifiers()="abstract"]/ClassBody/MethodDeclaration[Block[let$size:=count(*[not(self::EmptyStatement)])return$size=0or$size=1andReturnStatement[NullLiteralorNumericLiteral[@ValueAsInt=0]orStringLiteral[@Empty=true()]]]]Example(s):
publicabstractclassShouldBeAbstract{publicObjectcouldBeAbstract(){// Should be abstract method ?returnnull;}publicvoidcouldBeAbstract(){}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/EmptyMethodInAbstractClassShouldBeAbstract"/>Since: PMD 5.0
Priority: Medium Low (4)
No need to explicitly extend Object.
This rule is defined by the following XPath expression:
//ExtendsList/ClassType[pmd-java:typeIsExactly('java.lang.Object')]Example(s):
publicclassFooextendsObject{// not required}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/ExtendsObject"/>Since: PMD 5.0
Priority: Medium (3)
Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.FieldDeclarationsShouldBeAtStartOfClassRule
Example(s):
publicclassHelloWorldBean{// Field declared before methods / inner classes - OKprivateString_thing;publicStringgetMessage(){return"Hello World!";}// Field declared after methods / inner classes - avoid thisprivateString_fieldInWrongLocation;}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoreAnonymousClassDeclarations | true | Ignore field declarations, that are initialized with an anonymous class creation expression |
| ignoreInterfaceDeclarations | false | Ignore interface declarations that precede fields |
| ignoreEnumDeclarations | true | Ignore enum declarations that precede fields |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/FieldDeclarationsShouldBeAtStartOfClass"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/FieldDeclarationsShouldBeAtStartOfClass"><properties><propertyname="ignoreAnonymousClassDeclarations"value="true"/><propertyname="ignoreInterfaceDeclarations"value="false"/><propertyname="ignoreEnumDeclarations"value="true"/></properties></rule>Since: PMD 6.7.0
Priority: High (1)
Configurable naming conventions for field declarations. This rule reports variable declarationswhich do not match the regex that applies to their specific kind —e.g. constants (static final),enum constant, final field. Each regex can be configured through properties.
By default this rule uses the standard Java naming convention (Camel case), and uses the ALL_UPPERconvention for constants and enum constants.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.FieldNamingConventionsRule
Example(s):
classFoo{intmyField=1;// This is in camel case, so it's okintmy_Field=1;// This contains an underscore, it's not ok by default// but you may allow it, or even require the "my_" prefixfinalintFinalField=1;// you may configure a different convention for final fields,// e.g. here PascalCase: [A-Z][a-zA-Z0-9]*interfaceInterface{doublePI=3.14;// interface "fields" use the constantPattern property}enumAnEnum{ORG,NET,COM;// These use a separate property but are set to ALL_UPPER by default}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| publicConstantPattern | [A-Z][A-Z_0-9]* | Regex which applies to public constant names |
| constantPattern | [A-Z][A-Z_0-9]* | Regex which applies to non-public static final field names |
| enumConstantPattern | [A-Z][A-Z_0-9]* | Regex which applies to enum constant names |
| finalFieldPattern | [a-z][a-zA-Z0-9]* | Regex which applies to final field names |
| staticFieldPattern | [a-z][a-zA-Z0-9]* | Regex which applies to static field names |
| defaultFieldPattern | [a-z][a-zA-Z0-9]* | Regex which applies to field names |
| exclusions | serialVersionUID , serialPersistentFields | Names of fields to whitelist. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/FieldNamingConventions"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/FieldNamingConventions"><properties><propertyname="publicConstantPattern"value="[A-Z][A-Z_0-9]*"/><propertyname="constantPattern"value="[A-Z][A-Z_0-9]*"/><propertyname="enumConstantPattern"value="[A-Z][A-Z_0-9]*"/><propertyname="finalFieldPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="staticFieldPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="defaultFieldPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="exclusions"value="serialVersionUID,serialPersistentFields"/></properties></rule>Since: PMD 6.42.0
Priority: High (1)
Declaring a method parameter as final for an interface method is useless because the implementation may choose to not respect it.
This rule is defined by the following XPath expression:
//MethodDeclaration[FormalParameters/FormalParameter[@Final=true()]][not(Block)]Example(s):
publicinterfaceMyInterface{voidprocess(finalObjectarg);// Avoid using final here}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/FinalParameterInAbstractMethod"/>Since: PMD 1.02
Priority: Medium (3)
Some for loops can be simplified to while loops, this makes them more concise.
This rule is defined by the following XPath expression:
//ForStatement[not(ForInit|ForUpdate)andcount(*)=2]Example(s):
publicclassFoo{voidbar(){for(;true;)true;// No Init or Update part, may as well be: while (true)}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/ForLoopShouldBeWhileLoop"/>Since: PMD 6.6.0
Priority: High (1)
Configurable naming conventions for formal parameters of methods and lambdas.This rule reports formal parameters which do not match the regex that applies to theirspecific kind (e.g. lambda parameter, or final formal parameter). Each regex can beconfigured through properties.
By default this rule uses the standard Java naming convention (Camel case).
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.FormalParameterNamingConventionsRule
Example(s):
classFoo{abstractvoidbar(intmyInt);// This is Camel case, so it's okvoidbar(intmy_i){// this will be reported}voidlambdas(){// lambdas parameters can be configured separatelyConsumer<String>lambda1=s_str->{};// lambda parameters with an explicit type can be configured separatelyConsumer<String>lambda1=(Stringstr)->{};}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| methodParameterPattern | [a-z][a-zA-Z0-9]* | Regex which applies to formal parameter names |
| finalMethodParameterPattern | [a-z][a-zA-Z0-9]* | Regex which applies to final formal parameter names |
| lambdaParameterPattern | [a-z][a-zA-Z0-9]* | Regex which applies to inferred-type lambda parameter names |
| explicitLambdaParameterPattern | [a-z][a-zA-Z0-9]* | Regex which applies to explicitly-typed lambda parameter names |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/FormalParameterNamingConventions"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/FormalParameterNamingConventions"><properties><propertyname="methodParameterPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="finalMethodParameterPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="lambdaParameterPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="explicitLambdaParameterPattern"value="[a-z][a-zA-Z0-9]*"/></properties></rule>Deprecated
Since: PMD 4.2.6
Priority: Medium Low (4)
Names for references to generic values should be limited to a single uppercase letter.
Deprecated: This rule is deprecated since PMD 7.17.0 and will be removed with PMD 8.0.0. This rule has been replaced byTypeParameterNamingConventions, which provides more comprehensive and configurable naming conventions for type parameters.
This rule is defined by the following XPath expression:
//TypeParameter[string-length(@Name)>1orupper-case(@Name)!=@Name]Example(s):
publicinterfaceGenericDao<EextendsBaseModel,KextendsSerializable>extendsBaseDao{// This is ok...}publicinterfaceGenericDao<EextendsBaseModel,KextendsSerializable>{// Also this}publicinterfaceGenericDao<eextendsBaseModel,KextendsSerializable>{// 'e' should be an 'E'}publicinterfaceGenericDao<EFextendsBaseModel,KextendsSerializable>{// 'EF' is not ok.}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/GenericsNaming"/>Since: PMD 6.4.0
Priority: Medium (3)
Minimum Language Version: Java 1.7
Identicalcatch branches use up vertical space and increase the complexity of code withoutadding functionality. It’s better style to collapse identical branches into a single multi-catchbranch.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.IdenticalCatchBranchesRule
Example(s):
try{// do something}catch(IllegalArgumentExceptione){throwe;}catch(IllegalStateExceptione){// Can be collapsed into the previous blockthrowe;}try{// do something}catch(IllegalArgumentException|IllegalStateExceptione){// This is betterthrowe;}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/IdenticalCatchBranches"/>Since: PMD 7.1.0
Priority: Medium (3)
This rule reports lambda expressions that can be written more succinctly as a method reference. This is the case if the lambda is an expression lambda that only calls one method, passing the entire lambda parameter list in order to the method. For instance:
x->Foo.call(x)// can be Foo::callx->call(x)// can be this::call, if call is an instance method(x,y,z)->call(x,y,z)// can be this::call()->foo.get()// can be foo::getx->x.foo()// can be XType::foo (where XType is the type of x)In some cases rewriting a lambda to a method reference can change the semantics of the code. For instance in(x) -> someVar.call(x), the invocation of the lambda may produce a NullPointerException (NPE) ifsomeVar is null. The method referencesomeVar::call will also NPE ifsomeVar is null, but it will do so at the point the method reference is created, while the lambda is created without error and its NPE is only thrown if the lambda is invoked (which may be never). Code should probably not rely on this subtle semantic difference, therefore these potentially problematic lambdas are also reported by default. This behavior can be disabled by setting the propertyignoreIfMayNPE totrue.
The propertyignoreIfMayNPE is true by default. By default, calls whose receiver is itself a method call are ignored, because they could cause side effects. This may be changed by setting the propertyignoreIfReceiverIsMethod tofalse.
Scope limitations:
x -> new CtorCall().something(x), because the semantics of the method reference would be to create a single new object, while the lambda creates one object per invocation.(x) -> sideEffectingMethod().foo(x) will be reported. Suppress the warning in this case.This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.LambdaCanBeMethodReferenceRule
Example(s):
importjava.util.stream.Stream;publicclassLambdaCanBeMethodReference{static{Stream.of("abc","d").mapToInt(s->s.length())// could be String::length.reduce((x,y)->Integer.sum(x,y))// could be Integer::sum.getAsInt();}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoreIfMayNPE | false | Ignore lambdas that may throw a null pointer exception (NPE) when converted to a method reference. Those expressions will NPE at mref creation time, while the equivalent lambda would NPE only when invoked (which may be never). |
| ignoreIfReceiverIsMethod | true | Ignore if the receiver of the method reference is a method call. These may cause side effects that often should prevent the conversion to a method reference. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/LambdaCanBeMethodReference"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/LambdaCanBeMethodReference"><properties><propertyname="ignoreIfMayNPE"value="false"/><propertyname="ignoreIfReceiverIsMethod"value="true"/></properties></rule>Since: PMD 6.7.0
Priority: Medium (3)
This rule finds Linguistic Naming Antipatterns. It checks for fields, that are named, as if they shouldbe boolean but have a different type. It also checks for methods, that according to their name, shouldreturn a boolean, but don’t. Further, it checks, that getters return something and setters won’t.Finally, it checks that methods, that start with "to" - so called transform methods - actually returnsomething, since according to their name, they should convert or transform one object into another.There is additionally an option, to check for methods that contain "To" in their name - which arealso transform methods. However, this is disabled by default, since this detection is prone tofalse positives.
For more information, seeLinguistic Antipatterns - What They Are and HowDevelopers Perceive Them.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.LinguisticNamingRule
Example(s):
publicclassLinguisticNaming{intisValid;// the field name indicates a boolean, but it is an int.booleanisTrue;// correct type of the fieldvoidmyMethod(){inthasMoneyLocal;// the local variable name indicates a boolean, but it is an int.booleanhasSalaryLocal;// correct naming and type}// the name of the method indicates, it is a boolean, but the method returns an int.intisValid(){return1;}// correct naming and return typebooleanisSmall(){returntrue;}// the name indicates, this is a setter, but it returns somethingintsetName(){return1;}// the name indicates, this is a getter, but it doesn't return anythingvoidgetName(){// nothing to return?}// the name indicates, it transforms an object and should return the resultvoidtoDataType(){// nothing to return?}// the name indicates, it transforms an object and should return the resultvoidgrapeToWine(){// nothing to return?}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoredAnnotations | java.lang.Override | Fully qualified names of the annotation types that should be ignored by this rule |
| checkBooleanMethod | true | Check method names and types for inconsistent naming. |
| checkGetters | true | Check return type of getters. |
| checkSetters | true | Check return type of setters. |
| checkPrefixedTransformMethods | true | Check return type of methods whose names start with the configured prefix (see transformMethodNames property). |
| checkTransformMethods | false | Check return type of methods which contain the configured infix in their name (see transformMethodNames property). |
| booleanMethodPrefixes | is , has , can , have , will , should | The prefixes of methods that return boolean. |
| transformMethodNames | to , as | The prefixes and infixes that indicate a transform method. |
| checkFields | true | Check field names and types for inconsistent naming. |
| checkVariables | true | Check local variable names and types for inconsistent naming. |
| booleanFieldPrefixes | is , has , can , have , will , should | The prefixes of fields and variables that indicate boolean. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/LinguisticNaming"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/LinguisticNaming"><properties><propertyname="ignoredAnnotations"value="java.lang.Override"/><propertyname="checkBooleanMethod"value="true"/><propertyname="checkGetters"value="true"/><propertyname="checkSetters"value="true"/><propertyname="checkPrefixedTransformMethods"value="true"/><propertyname="checkTransformMethods"value="false"/><propertyname="booleanMethodPrefixes"value="is,has,can,have,will,should"/><propertyname="transformMethodNames"value="to,as"/><propertyname="checkFields"value="true"/><propertyname="checkVariables"value="true"/><propertyname="booleanFieldPrefixes"value="is,has,can,have,will,should"/></properties></rule>Since: PMD 4.0
Priority: Medium Low (4)
The Local Home interface of a Session EJB should be suffixed by ‘LocalHome’.
This rule is defined by the following XPath expression:
//ClassDeclaration[pmd-java:typeIs('javax.ejb.EJBLocalHome')andnot(ends-with(@SimpleName,'LocalHome'))]Example(s):
publicinterfaceMyBeautifulLocalHomeextendsjavax.ejb.EJBLocalHome{}// proper namepublicinterfaceMissingProperSuffixextendsjavax.ejb.EJBLocalHome{}// non-standard nameUse this rule by referencing it:
<ruleref="category/java/codestyle.xml/LocalHomeNamingConvention"/>Since: PMD 4.0
Priority: Medium Low (4)
The Local Interface of a Session EJB should be suffixed by ‘Local’.
This rule is defined by the following XPath expression:
//ClassDeclaration[pmd-java:typeIs('javax.ejb.EJBLocalObject')andnot(ends-with(@SimpleName,'Local'))]Example(s):
publicinterfaceMyLocalextendsjavax.ejb.EJBLocalObject{}// proper namepublicinterfaceMissingProperSuffixextendsjavax.ejb.EJBLocalObject{}// non-standard nameUse this rule by referencing it:
<ruleref="category/java/codestyle.xml/LocalInterfaceSessionNamingConvention"/>Since: PMD 2.2
Priority: Medium (3)
A local variable assigned only once can be declared final.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.LocalVariableCouldBeFinalRule
Example(s):
publicclassBar{publicvoidfoo(){StringtxtA="a";// if txtA will not be assigned again it is better to do this:finalStringtxtB="b";}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoreForEachDecl | false | Ignore non-final loop variables in a for-each statement. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/LocalVariableCouldBeFinal"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/LocalVariableCouldBeFinal"><properties><propertyname="ignoreForEachDecl"value="false"/></properties></rule>Since: PMD 6.6.0
Priority: High (1)
Configurable naming conventions for local variable declarations and other locally-scopedvariables. This rule reports variable declarations which do not match the regex that applies to theirspecific kind (e.g. final variable, or catch-clause parameter). Each regex can be configured throughproperties.
By default this rule uses the standard Java naming convention (Camel case).
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.LocalVariableNamingConventionsRule
Example(s):
classFoo{voidbar(){intlocalVariable=1;// This is in camel case, so it's okintlocal_variable=1;// This will be reported unless you change the regexfinalinti_var=1;// final local variables can be configured separatelytry{foo();}catch(IllegalArgumentExceptione_illegal){// exception block parameters can be configured separately}}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| localVarPattern | [a-z][a-zA-Z0-9]* | Regex which applies to non-final local variable names |
| finalVarPattern | [a-z][a-zA-Z0-9]* | Regex which applies to final local variable names |
| catchParameterPattern | [a-z][a-zA-Z0-9]* | Regex which applies to exception block parameter names |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/LocalVariableNamingConventions"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/LocalVariableNamingConventions"><properties><propertyname="localVarPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="finalVarPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="catchParameterPattern"value="[a-z][a-zA-Z0-9]*"/></properties></rule>Since: PMD 0.3
Priority: Medium (3)
Fields, formal arguments, or local variable names that are too long can make the code difficult to follow.
This rule is defined by the following XPath expression:
//VariableId[string-length(@Name)>$minimum]Example(s):
publicclassSomething{intreallyLongIntName=-3;// VIOLATION - Fieldpublicstaticvoidmain(StringargumentsList[]){// VIOLATION - FormalintotherReallyLongName=-5;// VIOLATION - Localfor(intinterestingIntIndex=0;// VIOLATION - ForinterestingIntIndex<10;interestingIntIndex++){}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| minimum | 17 | The variable length reporting threshold |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/LongVariable"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/LongVariable"><properties><propertyname="minimum"value="17"/></properties></rule>Since: PMD 4.0
Priority: Medium Low (4)
The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by ‘Bean’.
This rule is defined by the following XPath expression:
//ClassDeclaration[(pmd-java:typeIs('javax.ejb.SessionBean')orpmd-java:typeIs('javax.ejb.MessageDrivenBean'))andnot(ends-with(@SimpleName,'Bean'))]Example(s):
publicclassSomeBeanimplementsSessionBean{}// proper namepublicclassMissingTheProperSuffiximplementsSessionBean{}// non-standard nameUse this rule by referencing it:
<ruleref="category/java/codestyle.xml/MDBAndSessionBeanNamingConvention"/>Since: PMD 2.2
Priority: Medium (3)
Reports method and constructor parameters that can be made final because they are never reassigned within the body of the method.
This rule ignores unused parameters so as not to overlap with the ruleUnusedFormalParameter.It will also ignore the parameters of abstract methods.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.MethodArgumentCouldBeFinalRule
Example(s):
classFoo{// reported, parameter can be declared finalpublicStringfoo1(Stringparam){returnparam;}// not reported, parameter is declared finalpublicStringfoo2(finalStringparam){returnparam.trim();}// not reported because param is unusedpublicStringunusedParam(Stringparam){return"abc";}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/MethodArgumentCouldBeFinal"/>Since: PMD 1.2
Priority: High (1)
Configurable naming conventions for method declarations. This rule reportsmethod declarations which do not match the regex that applies to theirspecific kind (e.g. JUnit test or native method). Each regex can beconfigured through properties.
By default, this rule uses the standard Java naming convention (Camel case).
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.MethodNamingConventionsRule
Example(s):
publicclassFoo{publicvoidfooStuff(){}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| methodPattern | [a-z][a-zA-Z0-9]* | Regex which applies to instance method names |
| staticPattern | [a-z][a-zA-Z0-9]* | Regex which applies to static method names |
| nativePattern | [a-z][a-zA-Z0-9]* | Regex which applies to native method names |
| junit3TestPattern | test[A-Z0-9][a-zA-Z0-9]* | Regex which applies to JUnit 3 test method names |
| junit4TestPattern | [a-z][a-zA-Z0-9]* | Regex which applies to JUnit 4 test method names |
| junit5TestPattern | [a-z][a-zA-Z0-9]* | Regex which applies to JUnit 5 test method names |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/MethodNamingConventions"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/MethodNamingConventions"><properties><propertyname="methodPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="staticPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="nativePattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="junit3TestPattern"value="test[A-Z0-9][a-zA-Z0-9]*"/><propertyname="junit4TestPattern"value="[a-z][a-zA-Z0-9]*"/><propertyname="junit5TestPattern"value="[a-z][a-zA-Z0-9]*"/></properties></rule>Since: PMD 7.17.0
Priority: High (1)
Enforces the modifier order recommended by the JLS. Apart from sorting modifiers,this rule also enforces that all annotations appear before all modifier keywords.By setting the propertytypeAnnotations, you can also enforce that typeannotations appear right of the modifier keywords, next to the type they apply to.This property can have three values:
on type: Type annotations must be placed next to the type they apply toon decl: Type annotations must be placed with other annotations, before modifiers.This is not enforced if the type annotations syntactically appears within the type, e.g.inpublic Map.@Nullable Entry<K,V> method().anywhere (default): Either position fits. They still cannot be interspersed within keywordmodifiers. Annotations that are not type annotations are still required to be before keywordmodifiers.This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.ModifierOrderRule
Example(s):
abstractpublicclassFoo{// Warn: `public` should appear before `abstract`// This order is not recommended, annotations should appear before keyword modifiers,// and may appear after if they are type annotations.public@OverridestaticfooStuff(){}// This order is ok if property typeAnnotations is "anywhere", and enforced if it is "on decl":@NullablepublicObjectfooStuff(){}// This order is ok if property typeAnnotations is "anywhere", and enforced if it is "on type":public@NullableObjectfooStuff(){}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| typeAnnotations | anywhere | Whether type annotations should be placed next to the type they qualify and not before modifiers. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/ModifierOrder"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/ModifierOrder"><properties><propertyname="typeAnnotations"value="anywhere"/></properties></rule>Since: PMD 3.3
Priority: Medium (3)
Detects when a class, interface, enum or annotation does not have a package definition.
This rule is defined by the following XPath expression:
/CompilationUnit[not(PackageDeclaration)]/*[pmd-java:nodeIs("TypeDeclaration")][1]Example(s):
// no package declarationpublicclassClassInDefaultPackage{}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/NoPackage"/>Since: PMD 1.0
Priority: Medium (3)
A method should have only one exit point, and that should be the last statement in the method.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.OnlyOneReturnRule
Example(s):
publicclassOneReturnOnly1{publicStringfoo(intx){if(x>0){return"hey";// first exit}return"hi";// second exit}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/OnlyOneReturn"/>Since: PMD 3.3
Priority: Medium (3)
Detects when a package definition contains uppercase characters.
This rule is defined by the following XPath expression:
//PackageDeclaration[lower-case(@Name)!=@Name]Example(s):
packagecom.MyCompany;// should be lowercase namepublicclassSomeClass{}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/PackageCase"/>Since: PMD 5.0
Priority: Medium (3)
Checks for variables that are defined before they might be used. A declaration isdeemed to be premature if there are some statements that may return or throw anexception between the time the variable is declared and the time it is first read.
Some variables cannot be declared close to their first usage because of side-effectsoccurring before they’re first used. We try to avoid reporting those by consideringmost method and constructor invocations to be impure. See the second example.
Note that this rule is meant to improve code readability but is not an optimization.A smart JIT will not care whether the variable is declared prematurely or not, as itcan reorder code.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.PrematureDeclarationRule
Example(s):
publicintgetLength(String[]strings){intlength=0;// could be moved closer to the loopif(strings==null||strings.length==0)return0;for(Stringstr:strings){length+=str.length();}returnlength;}publicintgetLength(String[]strings){intstartTime=System.nanoTime();// cannot be moved because initializer is impureif(strings==null||strings.length==0){// some error logicthrownewSomeException(...);}for(Stringstr:strings){length+=str.length();}returnSystem.nanoTime()-startTime;}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/PrematureDeclaration"/>Since: PMD 4.0
Priority: Medium Low (4)
Remote Interface of a Session EJB should not have a suffix.
This rule is defined by the following XPath expression:
//ClassDeclaration[pmd-java:typeIs('javax.ejb.EJBObject')andmatches(@SimpleName,'.*(Session|EJB|Bean)$')]Example(s):
/* Poor Session suffix */publicinterfaceBadSuffixSessionextendsjavax.ejb.EJBObject{}/* Poor EJB suffix */publicinterfaceBadSuffixEJBextendsjavax.ejb.EJBObject{}/* Poor Bean suffix */publicinterfaceBadSuffixBeanextendsjavax.ejb.EJBObject{}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/RemoteInterfaceNamingConvention"/>Since: PMD 4.0
Priority: Medium Low (4)
A Remote Home interface type of a Session EJB should be suffixed by ‘Home’.
This rule is defined by the following XPath expression:
//ClassDeclaration[pmd-java:typeIs('javax.ejb.EJBHome')andnot(ends-with(@SimpleName,'Home'))]Example(s):
publicinterfaceMyBeautifulHomeextendsjavax.ejb.EJBHome{}// proper namepublicinterfaceMissingProperSuffixextendsjavax.ejb.EJBHome{}// non-standard nameUse this rule by referencing it:
<ruleref="category/java/codestyle.xml/RemoteSessionInterfaceNamingConvention"/>Since: PMD 5.0
Priority: Medium Low (4)
Short Classnames with fewer than e.g. five characters are not recommended.
This rule is defined by the following XPath expression:
//ClassDeclaration[string-length(@SimpleName)<$minimum]Example(s):
publicclassFoo{}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| minimum | 5 | Number of characters that are required as a minimum for a class name. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/ShortClassName"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/ShortClassName"><properties><propertyname="minimum"value="5"/></properties></rule>Since: PMD 0.3
Priority: Medium (3)
Method names that are very short are not helpful to the reader.
This rule is defined by the following XPath expression:
//MethodDeclaration[string-length(@Name)<$minimum]Example(s):
publicclassShortMethod{publicvoida(inti){// Violation}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| minimum | 3 | Number of characters that are required as a minimum for a method name. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/ShortMethodName"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/ShortMethodName"><properties><propertyname="minimum"value="3"/></properties></rule>Since: PMD 0.3
Priority: Medium (3)
Fields, local variables, enum constant names or parameter names that are very short are not helpful to the reader.
This rule is defined by the following XPath expression:
//VariableId[string-length(@Name)<$minimum](: ForStatement :)[not(../../parent::ForInit)](: Foreach statement :)[not(../../parent::ForeachStatement)](: Catch statement parameter :)[not(parent::CatchParameter)](: Lambda expression parameter :)[not(parent::LambdaParameter)](: Exclude Unnamed Variables (JEP 456) :)[@Unnamed=false()]Example(s):
publicclassSomething{privateintq=15;// field - too shortpublicstaticvoidmain(Stringas[]){// formal arg - too shortintr=20+q;// local var - too shortfor(inti=0;i<10;i++){// not a violation (inside 'for' loop)r+=q;}for(Integeri:numbers){// not a violation (inside 'for-each' loop)r+=q;}}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| minimum | 3 | Number of characters that are required as a minimum for a variable name. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/ShortVariable"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/ShortVariable"><properties><propertyname="minimum"value="3"/></properties></rule>Since: PMD 4.1
Priority: Medium (3)
If you overuse the static import feature, it can make your program unreadable andunmaintainable, 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 knowwhich class a static member comes from (Sun 1.5 Language Guide).
This rule is defined by the following XPath expression:
.[count(ImportDeclaration[@Static=true()])>$maximumStaticImports]Example(s):
importstaticLennon;importstaticRingo;importstaticGeorge;importstaticPaul;importstaticYoko;// Too much !This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| maximumStaticImports | 4 | All static imports can be disallowed by setting this to 0 |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/TooManyStaticImports"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/TooManyStaticImports"><properties><propertyname="maximumStaticImports"value="4"/></properties></rule>Since: PMD 7.17.0
Priority: Medium Low (4)
Configurable naming conventions for type parameters in generic types and methods.This rule reports type parameter declarations which do not match the configured regex.Type parameters can appear on classes, interfaces, enums, records, and methods.
By default, this rule uses the standard Java naming convention (single uppercase letter).
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.TypeParameterNamingConventionsRule
Example(s):
// Generic types - validpublicinterfaceRepository<T>{}publicclassCache<K,V>{}// Generic types - invalidpublicinterfaceRepository<type>{}// lowercasepublicclassCache<KEY,VALUE>{}// multiple letters// Generic methods - validpublicclassUtil{publicstatic<T>Tidentity(Tvalue){returnvalue;}public<T,R>Rtransform(Tinput,Function<T,R>mapper){}}// Generic methods - invalidpublicclassUtil{publicstatic<element>elementget(elementvalue){}// lowercasepublic<INPUT,OUTPUT>OUTPUTconvert(INPUTin){}// multiple letters}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| typeParameterNamePattern | [A-Z] | Regex which applies to type parameter names |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/TypeParameterNamingConventions"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/TypeParameterNamingConventions"><properties><propertyname="typeParameterNamePattern"value="[A-Z]"/></properties></rule>Since: PMD 6.2.0
Priority: Medium (3)
Avoid the use of value in annotations when it’s the only element.
This rule is defined by the following XPath expression:
//Annotation/AnnotationMemberList[count(*)=1andMemberValuePair[@Shorthand=false()and@Name='value']]Example(s):
@TestClassAnnotation(value="TEST")publicclassFoo{@TestMemberAnnotation(value="TEST")privateStringy;@TestMethodAnnotation(value="TEST")publicvoidbar(){intx=42;return;}}// should be@TestClassAnnotation("TEST")publicclassFoo{@TestMemberAnnotation("TEST")privateStringy;@TestMethodAnnotation("TEST")publicvoidbar(){intx=42;return;}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| java7Compatibility | false | If disabled, the rule shows also violations that are applicable for java8+ |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/UnnecessaryAnnotationValueElement"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/UnnecessaryAnnotationValueElement"><properties><propertyname="java7Compatibility"value="false"/></properties></rule>Since: PMD 7.0.0
Priority: Medium (3)
Minimum Language Version: Java 1.5
Reports explicit boxing and unboxing conversions that may safely be removed,either because they would be inserted by the compiler automatically,or because they’re semantically a noop (eg unboxing a value to rebox it immediately).
Note that this only handles boxing and unboxing conversions occurring throughcalls tovalueOf or one of theintValue,byteValue, etc. methods. Caststhat command a conversion are reported byUnnecessaryCast instead.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryBoxingRule
Example(s):
{// Instead ofIntegerinteger=Integer.valueOf(2);// you may just writeIntegerinteger=2;inti=integer.intValue();// similarly for unboxing// Instead ofintx=Integer.valueOf("42");// you may just writeintx=Integer.parseInt("42");}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/UnnecessaryBoxing"/>Since: PMD 6.24.0
Priority: Medium (3)
Minimum Language Version: Java 1.5
Detects casts which could be removed as the operand of the cast is already suitablefor the context type. For instance, in the following:
Object context = (Comparable) "o";The cast is unnecessary. This is becauseString already is a subtype of bothComparable andObject.
This will also flag casts that can be avoided because of the autoboxing feature of Java 5.
Integer integer = (Integer) 1;The literal would be autoboxed toInteger anyway.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryCastRule
Example(s):
importjava.util.function.Function;classSomeClass{static{Objecto;longl;inti;IntegerboxedInt;// reference conversionso=(Object)newSomeClass();// unnecessaryo=(SomeClass)o;// necessary (narrowing cast)o=(Comparable<String>)"string";// unnecessary// primitive conversionsl=(long)2;// unnecessaryl=(long)2.0;// necessary (narrowing cast)l=(byte)i;// necessary (narrowing cast)// boxing/unboxing casts (since java 5)o=(Integer)3;// unnecessary (autoboxing would apply)o=(long)3;// necessary (would be boxed to Long)l=(int)boxedInt;// necessary (cannot cast Integer to long)// casts that give a target type to a lambda/ method ref are necessaryo=(Function<Integer,String>)Integer::toString;// necessary (no target type)}}importjava.util.*;classSomeClass{static{/* Casts involving access to collections were common before Java 5, because collections * were not generic. This rule may hence be useful when converting from using a raw * type like `List` to a parameterized type like `List<String>`. */List<String>stringList=Arrays.asList("a","b");Stringelement=(String)stringList.get(0);// this cast is unnecessary}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/UnnecessaryCast"/>Since: PMD 1.0
Priority: Medium (3)
This rule detects when a constructor is not necessary; i.e., when there is only one constructor and theconstructor is identical to the default constructor. The default constructor should has same accessmodifier as the declaring class. In an enum type, the default constructor is implicitly private.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryConstructorRule
Example(s):
publicclassFoo{publicFoo(){}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoredAnnotations | javax.inject.Inject , com.google.inject.Inject , org.springframework.beans.factory.annotation.Autowired | Fully qualified names of the annotation types that should be ignored by this rule |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/UnnecessaryConstructor"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/UnnecessaryConstructor"><properties><propertyname="ignoredAnnotations"value="javax.inject.Inject,com.google.inject.Inject,org.springframework.beans.factory.annotation.Autowired"/></properties></rule>Since: PMD 5.0
Priority: Medium Low (4)
Import statements allow the use of non-fully qualified names. The use of a fully qualified namewhich is covered by an import statement is redundant. Consider using the non-fully qualified name.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryFullyQualifiedNameRule
Example(s):
importjava.util.List;publicclassFoo{privatejava.util.Listlist1;// Unnecessary FQNprivateListlist2;// More appropriate given import of 'java.util.List'}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| reportStaticMethods | true | Report unnecessary static method qualifiers like inCollections.emptyList(), if the method is imported or inherited. |
| reportStaticFields | true | Report unnecessary static field qualifiers like inMath.PI, if the field is imported or inherited. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/UnnecessaryFullyQualifiedName"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/UnnecessaryFullyQualifiedName"><properties><propertyname="reportStaticMethods"value="true"/><propertyname="reportStaticFields"value="true"/></properties></rule>Since: PMD 6.34.0
Priority: Medium Low (4)
Reports import statements that can be removed. They are either unused,duplicated, or the members they import are already implicitly in scope,because they’re in java.lang, or the current package.
If some imports cannot be resolved, for instance because you run PMD withan incomplete auxiliary classpath, some imports may be conservatively markedas used even if they’re not to avoid false positives.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryImportRule
Example(s):
importjava.io.File;// not used, can be removedimportjava.util.Collections;// used belowimportjava.util.*;// so this one is not usedimportjava.lang.Object;// imports from java.lang, unnecessaryimportjava.lang.Object;// duplicate, unnecessarypublicclassFoo{staticObjectemptyList(){returnCollections.emptyList();}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/UnnecessaryImport"/>Deprecated
Since: PMD 3.3
Priority: Medium (3)
Avoid the creation of unnecessary local variables.
This rule has been deprecated since 7.17.0. Use the new ruleVariableCanBeInlined instead, which additionally covers throw statements.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryLocalBeforeReturnRule
Example(s):
publicclassFoo{publicintfoo(){intx=doSomething();returnx;// instead, just 'return doSomething();'}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| statementOrderMatters | true | If set to false this rule no longer requires the variable declaration and return statement to be on consecutive lines. Any variable that is used solely in a return statement will be reported. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/UnnecessaryLocalBeforeReturn"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/UnnecessaryLocalBeforeReturn"><properties><propertyname="statementOrderMatters"value="true"/></properties></rule>Since: PMD 1.02
Priority: Medium (3)
Fields in interfaces and annotations are automaticallypublic static final, and methods arepublic abstract.Classes, interfaces or annotations nested in an interface or annotation are automaticallypublic static(all nested interfaces and annotations are automatically static).Nested enums are automaticallystatic.For historical reasons, modifiers which are implied by the context are accepted by the compiler, but are superfluous.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryModifierRule
Example(s):
public@interfaceAnnotation{publicabstractvoidbar();// both abstract and public are ignored by the compilerpublicstaticfinalintX=0;// public, static, and final all ignoredpublicstaticclassBar{}// public, static ignoredpublicstaticinterfaceBaz{}// ditto}publicinterfaceFoo{publicabstractvoidbar();// both abstract and public are ignored by the compilerpublicstaticfinalintX=0;// public, static, and final all ignoredpublicstaticclassBar{}// public, static ignoredpublicstaticinterfaceBaz{}// ditto}publicclassBar{publicstaticinterfaceBaz{}// static ignoredpublicstaticenumFooBar{// static ignoredFOO;}}publicclassFooClass{staticrecordBarRecord(){}// static ignored}publicinterfaceFooInterface{staticrecordBarRecord(){}// static ignored}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/UnnecessaryModifier"/>Since: PMD 1.3
Priority: Medium (3)
Avoid the use of unnecessary return statements. A return is unnecessary when noinstructions follow anyway.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryReturnRule
Example(s):
publicclassFoo{publicvoidbar(){intx=42;return;}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/UnnecessaryReturn"/>Since: PMD 6.46.0
Priority: Medium (3)
Reports unnecessary semicolons (so called "empty statements" and "empty declarations").These can be removed without changing the program. The Java grammarallows them for historical reasons, but they should be avoided.
This rule will not report empty statements that are syntactically required, for instance, because they are the body of a control statement.
This rule replaces EmptyStatementNotInLoop.
This rule is defined by the following XPath expression:
(: empty declarations :)//EmptyDeclaration(: empty statements :)|//Block/EmptyStatementExample(s):
classFoo{{toString();;// one of these semicolons is unnecessaryif(true);// this semicolon is not unnecessary, but it could be an empty block instead (not reported)}};// this semicolon is unnecessaryUse this rule by referencing it:
<ruleref="category/java/codestyle.xml/UnnecessarySemicolon"/>Since: PMD 6.11.0
Priority: Medium (3)
Minimum Language Version: Java 1.7
In some cases, explicit type arguments in a constructor call for a generic typemay be replaced by diamond type arguments (<>), and be inferred by the compiler.This rule recommends that you use diamond type arguments anywhere possible, sinceit avoids duplication of the type arguments, and makes the code more concise and readable.
This rule is useful when upgrading a codebase to Java 1.7, Java 1.8, or Java 9.The diamond syntax was first introduced in Java 1.7. In Java 8, improvements in Java’stype inference made more type arguments redundant. In Java 9, type arguments inferencewas made possible for anonymous class constructors.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.UseDiamondOperatorRule
Example(s):
importjava.util.*;classFoo{static{List<String>strings;strings=newArrayList<String>();// unnecessary duplication of type parametersstrings=newArrayList<>();// using diamond type arguments is more concisestrings=newArrayList();// accidental use of a raw type, you can use ArrayList<> insteadstrings=newArrayList<>(){// for anonymous classes, this is possible since Java 9 only};}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/UseDiamondOperator"/>Since: PMD 7.0.0
Priority: Medium (3)
Minimum Language Version: Java 10
Java 10 introduced thevar keyword. This reduces the amount of code written because java can infer the typefrom the initializer of the variable declaration.
This is essentially a trade-off: On the one hand, it can make code more readable by eliminating redundantinformation. On the other hand, it can make code less readable by eliding useful information. There is noblanket rule for whenvar should be used or shouldn’t.
It may make sense to usevar when the type is inherently clear upon reading the statement(ie: assignment to either a literal value or a constructor call). Those use casescan be enabled through properties.
Notice that lambda parameters are allowed, as they are already inferred by default (thevar keywordis completely optional).
See alsoLocal Variable Type Inference Style Guidelines.
This rule is defined by the following XPath expression:
//LocalVariableDeclaration[@TypeInferred=true()][not(VariableDeclarator[*[pmd-java:nodeIs("Literal")]])or$allowLiterals=false()][not(VariableDeclarator[ConstructorCall])or$allowCtors=false()][not(VariableDeclarator[CastExpression])or$allowCasts=false()][not(parent::ForeachStatement)or$allowLoopVariable=false()]This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| allowLiterals | false | Allow when variables are directly initialized with literals |
| allowCtors | false | Allow when variables are directly initialized with a constructor call |
| allowCasts | false | Allow when variables are directly initialized with a the result of a cast |
| allowLoopVariable | false | Allow when variables are used as loop variables in enhanced for loops |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/UseExplicitTypes"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/UseExplicitTypes"><properties><propertyname="allowLiterals"value="false"/><propertyname="allowCtors"value="false"/><propertyname="allowCasts"value="false"/><propertyname="allowLoopVariable"value="false"/></properties></rule>Since: PMD 5.0
Priority: Medium Low (4)
Parenthesized expressions are used to override the default operator precedencerules. Parentheses whose removal would not change the relative nesting of operatorsare unnecessary, because they don’t change the semantics of the enclosing expression.
Some parentheses that strictly speaking are unnecessary, may still be considered usefulfor readability. This rule allows to ignore violations on two kinds of unnecessary parentheses:
(a+b)&c// is equivalent to `a + b & c`, but probably clearerUnset the propertyignoreClarifying to report them.
(a==null)!=(b==null)a==null!=(b==null)The parentheses on the right are required, and the parentheses on the left arejust more visually pleasing. Unset the propertyignoreBalancing to report them.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.UselessParenthesesRule
Example(s):
publicclassFoo{{intn=0;n=(n);// heren=(n*2)*3;// and heren=n*(2*3);// and here}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoreClarifying | true | Ignore parentheses that separate expressions of difference precedence, like in(a % 2 == 0) ? x : -x |
| ignoreBalancing | true | Ignore unnecessary parentheses that appear balanced around an equality operator, because the other operand requires parentheses.For example, in(a == null) == (b == null), only the second pair of parentheses is necessary, but the expression is clearer that way. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/UselessParentheses"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/UselessParentheses"><properties><propertyname="ignoreClarifying"value="true"/><propertyname="ignoreBalancing"value="true"/></properties></rule>Since: PMD 5.4.0
Priority: Medium (3)
Reports qualified this usages in the same class.
This rule is defined by the following XPath expression:
//ThisExpression/ClassType[ancestor::*[pmd-java:nodeIs('TypeDeclaration')][1]/@SimpleName=./@SimpleName]Example(s):
publicclassFoo{finalFoootherFoo=Foo.this;// use "this" directlypublicvoiddoSomething(){finalFooanotherFoo=Foo.this;// use "this" directly}privateActionListenerreturnListener(){returnnewActionListener(){@OverridepublicvoidactionPerformed(ActionEvente){doSomethingWithQualifiedThis(Foo.this);// This is fine}};}privateclassFoo3{finalFoomyFoo=Foo.this;// This is fine}privateclassFoo2{finalFoo2myFoo2=Foo2.this;// Use "this" directly}}Use this rule by referencing it:
<ruleref="category/java/codestyle.xml/UselessQualifiedThis"/>Since: PMD 6.15.0
Priority: Medium (3)
When declaring and initializing array fields or variables, it is not necessary to explicitly create a new arrayusingnew. Instead one can simply define the initial content of the array as a expression in curly braces.
E.g.int[] x = new int[] { 1, 2, 3 }; can be written asint[] x = { 1, 2, 3 };.
This rule is defined by the following XPath expression:
//VariableDeclarator[VariableId[@TypeInferred=false()and@ArrayType=true()]][ArrayAllocation/ArrayInitializer]Example(s):
Foo[]x=newFoo[]{...};// Overly verboseFoo[]x={...};//Equivalent to above lineUse this rule by referencing it:
<ruleref="category/java/codestyle.xml/UseShortArrayInitializer"/>Since: PMD 6.10.0
Priority: Medium (3)
Minimum Language Version: Java 1.7
Since Java 1.7, numeric literals can use underscores to separate digits. This rule enforces thatnumeric literals above a certain length use these underscores to increase readability.
The rule only supports decimal (base 10) literals for now. The acceptable length under which literalsare not required to have underscores is configurable via a property. Even under that length, underscoresthat are misplaced (not making groups of 3 digits) are reported.
This rule is defined by the following XPath expression:
//NumericLiteral(: Filter out literals in base other than 10 :)[@Base=10](: Filter out ignored field name :)[not(ancestor::VariableDeclarator[1][@Name='serialVersionUID'])][some$numintokenize(@Image,"[dDfFlLeE+\-]")satisfiesnot((contains($num,".")andstring-length(substring-before($num,"."))<=$acceptableDecimalLengthandstring-length(substring-after($num,"."))<=$acceptableDecimalLengthorstring-length($num)<=$acceptableDecimalLength)andnot(contains($num,"_"))ormatches($num,"^[0-9]{1,3}(_[0-9]{3})*(\.([0-9]{3}_)*[0-9]{1,3})?$"))]Example(s):
publicclassFoo{privateintnum=1000000;// should be 1_000_000}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| acceptableDecimalLength | 4 | Length under which literals in base 10 are not required to have underscores |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/UseUnderscoresInNumericLiterals"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/UseUnderscoresInNumericLiterals"><properties><propertyname="acceptableDecimalLength"value="4"/></properties></rule>Since: PMD 7.17.0
Priority: Medium (3)
Local variables should not be declared and then immediately returned or thrown. Suchvariable declarations add unnecessary complexity and make the code harder to read.It is often simpler and cleaner to return or throw the value directly.
This rule implements SonarSource ruleS1488.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.codestyle.VariableCanBeInlinedRule
Example(s):
classFoo{Objectfoo(){varfoo="foo";returnfoo;// instead, just 'return "foo";'}Objectbar(){varex=getIllegalArgumentException();throwex;// instead, just 'throw getIllegalArgumentException();'}Objectbaz(){varbaz=switch(foo()){case"foo"->{varfoo=foo();yieldfoo;// Can be simplified to 'yield foo();'}case"bar"->{varbar=bar();yieldbar;// Can be simplified to 'yield bar();'}default->bar("baz");};returnbaz;// instead, just 'return switch (foo()) {...'}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| statementOrderMatters | true | If set to false this rule no longer requires the variable declaration and return/throw statement to be on consecutive lines. Any variable that is used solely in a return/throw statement will be reported. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/codestyle.xml/VariableCanBeInlined"/>Use this rule and customize it:
<ruleref="category/java/codestyle.xml/VariableCanBeInlined"><properties><propertyname="statementOrderMatters"value="true"/></properties></rule>