elx/gradle/quality/pmd/category/java/codestyle.xml

2177 lines
77 KiB
XML
Raw Permalink Normal View History

2023-05-26 17:16:55 +02:00
<?xml version="1.0"?>
<ruleset name="Code Style"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
<description>
Rules which enforce a specific coding style.
</description>
<rule name="AbstractNaming"
language="java"
since="1.4"
deprecated="true"
message="Abstract classes should be named 'AbstractXXX'"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#abstractnaming">
<description>
Abstract classes should be named 'AbstractXXX'.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
by {% rule java/codestyle/ClassNamingConventions %}.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration
[@Abstract='true' and @Interface='false']
[not (starts-with(@Image,'Abstract'))]
|
//ClassOrInterfaceDeclaration
[@Abstract='false']
[$strict='true']
[starts-with(@Image, 'Abstract')]
]]>
</value>
</property>
<property name="strict" type="Boolean" value="true" description="Also flag classes, that are named Abstract, but are not abstract."/>
</properties>
<example>
<![CDATA[
public abstract class Foo { // should be AbstractFoo
}
]]>
</example>
</rule>
<rule name="AtLeastOneConstructor"
language="java"
since="1.04"
message="Each class should declare at least one constructor"
class="net.sourceforge.pmd.lang.java.rule.codestyle.AtLeastOneConstructorRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#atleastoneconstructor">
<description>
<![CDATA[
Each non-static class should declare at least one constructor.
Classes with solely static members are ignored, refer to [UseUtilityClassRule](pmd_rules_java_design.html#useutilityclass) to detect those.
]]>
</description>
<priority>3</priority>
<example>
<![CDATA[
public class Foo {
// missing constructor
public void doSomething() { ... }
public void doOtherThing { ... }
}
]]>
</example>
</rule>
<rule name="AvoidDollarSigns"
since="1.5"
message="Avoid using dollar signs in variable/method/class/interface names"
class="net.sourceforge.pmd.lang.java.rule.codestyle.AvoidDollarSignsRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#avoiddollarsigns">
<description>
Avoid using dollar signs in variable/method/class/interface names.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class Fo$o { // not a recommended name
}
]]>
</example>
</rule>
<rule name="AvoidFinalLocalVariable"
language="java"
since="4.1"
class="net.sourceforge.pmd.lang.rule.XPathRule"
message="Avoid using final local variables, turn them into fields"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#avoidfinallocalvariable">
<description>Avoid using final local variables, turn them into fields.</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//LocalVariableDeclaration[
@Final = 'true'
and not(../../ForStatement)
and
(
(count(VariableDeclarator/VariableInitializer) = 0)
or
(VariableDeclarator/VariableInitializer/Expression/PrimaryExpression/PrimaryPrefix/Literal)
)
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class MyClass {
public void foo() {
final String finalLocalVariable;
}
}
]]>
</example>
</rule>
<rule name="AvoidPrefixingMethodParameters"
language="java"
since="5.0"
deprecated="true"
class="net.sourceforge.pmd.lang.rule.XPathRule"
message="Avoid prefixing parameters by in, out or inOut. Uses Javadoc to document this behavior."
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#avoidprefixingmethodparameters">
<description>
Prefixing parameters by 'in' or 'out' pollutes the name of the parameters and reduces code readability.
To indicate whether or not a parameter will be modify in a method, its better to document method
behavior with Javadoc.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
by the more general rule {% rule java/codestyle/FormalParameterNamingConventions %}.
</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodDeclaration/MethodDeclarator/FormalParameters/FormalParameter/VariableDeclaratorId[
pmd:matches(@Image,'^in[A-Z].*','^out[A-Z].*','^in$','^out$')
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
// Not really clear
public class Foo {
public void bar(
int inLeftOperand,
Result outRightOperand) {
outRightOperand.setValue(inLeftOperand * outRightOperand.getValue());
}
}
]]>
</example>
<example>
<![CDATA[
// Far more useful
public class Foo {
/**
*
* @param leftOperand, (purpose), not modified by method.
* @param rightOperand (purpose), will be modified by the method: contains the result.
*/
public void bar(
int leftOperand,
Result rightOperand) {
rightOperand.setValue(leftOperand * rightOperand.getValue());
}
}
]]>
</example>
</rule>
<rule name="AvoidProtectedFieldInFinalClass"
language="java"
since="2.1"
message="Avoid protected fields in a final class. Change to private or package access."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#avoidprotectedfieldinfinalclass">
<description>
Do not use protected fields in final classes since they cannot be subclassed.
Clarify your intent by using private or package access modifiers instead.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration[@Final='true']
/ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration
/FieldDeclaration[@Protected='true']
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public final class Bar {
private int x;
protected int y; // bar cannot be subclassed, so is y really private or package visible?
Bar() {}
}
]]>
</example>
</rule>
<rule name="AvoidProtectedMethodInFinalClassNotExtending"
language="java"
since="5.1"
message="Avoid protected methods in a final class that doesn't extend anything other than Object. Change to private or package access."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#avoidprotectedmethodinfinalclassnotextending">
<description>
Do not use protected methods in most final classes since they cannot be subclassed. This should
only be allowed in final classes that extend other classes with protected methods (whose
visibility cannot be reduced). Clarify your intent by using private or package access modifiers instead.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration[@Final='true' and not(ExtendsList)]
/ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration
/MethodDeclaration[@Protected='true'][MethodDeclarator/@Image != 'finalize']
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public final class Foo {
private int bar() {}
protected int baz() {} // Foo cannot be subclassed, and doesn't extend anything, so is baz() really private or package visible?
}
]]>
</example>
</rule>
<rule name="AvoidUsingNativeCode"
language="java"
since="4.1"
message="The use of native code is not recommended."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#avoidusingnativecode">
<description>
Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portability
and increases the maintenance burden.
</description>
<priority>2</priority>
<properties>
<property name="xpath">
<value>//Name[starts-with(@Image,'System.loadLibrary')]</value>
</property>
</properties>
<example>
<![CDATA[
public class SomeJNIClass {
public SomeJNIClass() {
System.loadLibrary("nativelib");
}
static {
System.loadLibrary("nativelib");
}
public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException {
System.loadLibrary("nativelib");
}
}
]]>
</example>
</rule>
<rule name="BooleanGetMethodName"
language="java"
since="4.0"
message="A 'getX()' method which returns a boolean should be named 'isX()'"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#booleangetmethodname">
<description>
Methods that return 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.
</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//MethodDeclaration[
MethodDeclarator[count(FormalParameters/FormalParameter) = 0 or $checkParameterizedMethods = 'true']
[starts-with(@Image, 'get')]
and
ResultType/Type/PrimitiveType[@Image = 'boolean']
and not(../Annotation//Name[@Image = 'Override'])
]
]]>
</value>
</property>
<property name="checkParameterizedMethods" type="Boolean" description="Check parameterized methods" value="false"/>
</properties>
<example>
<![CDATA[
public boolean getFoo(); // bad
public boolean isFoo(); // ok
public boolean getFoo(boolean bar); // ok, unless checkParameterizedMethods=true
]]>
</example>
</rule>
<rule name="CallSuperInConstructor"
language="java"
since="3.0"
message="It is a good practice to call super() in a constructor"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#callsuperinconstructor">
<description>
It is a good practice to call super() in a constructor. If super() is not called but
another constructor (such as an overloaded constructor) is called, this rule will not report it.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration[ count (ExtendsList/*) > 0 ]
/ClassOrInterfaceBody
/ClassOrInterfaceBodyDeclaration
/ConstructorDeclaration[ count (.//ExplicitConstructorInvocation)=0 ]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo extends Bar{
public Foo() {
// call the constructor of Bar
super();
}
public Foo(int code) {
// do something with code
this();
// no problem with this
}
}
]]>
</example>
</rule>
<rule name="ClassNamingConventions"
since="1.2"
message="The {0} name ''{1}'' doesn''t match ''{2}''"
class="net.sourceforge.pmd.lang.java.rule.codestyle.ClassNamingConventionsRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#classnamingconventions">
<description>
Configurable naming conventions for type declarations. This rule reports
type declarations which do not match the regex that applies to their
specific kind (e.g. enum or interface). Each regex can be configured through
properties.
By default this rule uses the standard Java naming convention (Pascal case),
and reports utility class names not ending with 'Util'.
</description>
<priority>1</priority>
<example>
<![CDATA[
// 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 names
public class FooBar {}
// 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+'
public abstract class Thing {}
// This class doesn't respect the convention, and will be flagged
public class Éléphant {}
]]>
</example>
</rule>
<rule name="CommentDefaultAccessModifier"
since="5.4.0"
class="net.sourceforge.pmd.lang.java.rule.codestyle.CommentDefaultAccessModifierRule"
message="Missing commented default access modifier"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#commentdefaultaccessmodifier">
<description>
To avoid mistakes if we want that a Method, Constructor, Field or Nested class have a default access modifier
we must add a comment at the beginning of it's 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. Use the
property "ignoredAnnotations" to customize the recognized annotations.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class Foo {
final String stringValue = "some string";
String getString() {
return stringValue;
}
class NestedFoo {
}
}
// should be
public class Foo {
/* default */ final String stringValue = "some string";
/* default */ String getString() {
return stringValue;
}
/* default */ class NestedFoo {
}
}
]]>
</example>
</rule>
<rule name="ConfusingTernary"
since="1.9"
message="Avoid if (x != y) ..; else ..;"
class="net.sourceforge.pmd.lang.java.rule.codestyle.ConfusingTernaryRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#confusingternary">
<description>
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 this
rule makes the code easier to read. Also, this resolves trivial ordering problems, such
as "does the error case go first?" or "does the common case go first?".
</description>
<priority>3</priority>
<example>
<![CDATA[
boolean bar(int x, int y) {
return (x != y) ? diff : same;
}
]]>
</example>
</rule>
<rule name="ControlStatementBraces"
language="java"
since="6.2.0"
message="This statement should have braces"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#controlstatementbraces">
<description>
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, and
helps prepare the future when you need to add another statement. That said, this rule lets you control
which statements are required to have braces via properties.
From 6.2.0 on, this rule supersedes WhileLoopMustUseBraces, ForLoopMustUseBraces, IfStmtMustUseBraces,
and IfElseStmtMustUseBraces.
</description>
<priority>3</priority>
<properties>
<property name="checkIfElseStmt" type="Boolean" value="true" description="Require that 'if ... else' statements use braces" />
<property name="checkSingleIfStmt" type="Boolean" value="true" description="Require that 'if' statements with a single branch use braces" />
<property name="checkWhileStmt" type="Boolean" value="true" description="Require that 'while' loops use braces" />
<property name="checkForStmt" type="Boolean" value="true" description="Require that 'for' loops should use braces" />
<property name="checkDoWhileStmt" type="Boolean" value="true" description="Require that 'do ... while' loops use braces" />
<property name="checkCaseStmt" type="Boolean" value="false" description="Require that cases of a switch have braces"/>
<property name="allowEmptyLoop" type="Boolean" value="false" description="Allow loops with an empty statement, e.g. 'while(true);'" />
<property name="version" value="2.0"/>
<property name="xpath">
<value><![CDATA[
//WhileStatement[$checkWhileStmt and not(Statement/Block) and not($allowEmptyLoop and Statement/EmptyStatement)]
|
//ForStatement[$checkForStmt and not(Statement/Block) and not($allowEmptyLoop and Statement/EmptyStatement)]
|
//DoStatement[$checkDoWhileStmt and not(Statement/Block) and not($allowEmptyLoop and Statement/EmptyStatement)]
|
(: The violation is reported on the sub statement -- not the if statement :)
//Statement[$checkIfElseStmt and parent::IfStatement and not(child::Block or child::IfStatement)
(: Whitelists single if statements :)
and ($checkSingleIfStmt
(: Inside this not(...) is the definition of a "single if statement" :)
or not(count(../Statement) = 1 (: No else stmt :)
(: Not the last branch of an 'if ... else if' chain :)
and not(parent::IfStatement[parent::Statement[parent::IfStatement]])))]
|
(: Reports case labels if one of their subordinate statements is not braced :)
//SwitchLabel[$checkCaseStmt]
[count(following-sibling::BlockStatement except following-sibling::SwitchLabel[1]/following-sibling::BlockStatement) > 1
or (some $stmt (: in only the block statements until the next label :)
in following-sibling::BlockStatement except following-sibling::SwitchLabel[1]/following-sibling::BlockStatement
satisfies not($stmt/Statement/Block))]
]]></value>
</property>
</properties>
<example>
<![CDATA[
while (true) // not recommended
x++;
while (true) { // preferred approach
x++;
}
]]>
</example>
</rule>
<rule name="DefaultPackage"
language="java"
since="3.4"
message="Use explicit scoping instead of the default package private level"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#defaultpackage">
<description>
Use explicit scoping instead of accidental usage of default package private level.
The rule allows methods and fields annotated with Guava's @VisibleForTesting.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration[@Interface='false']
/ClassOrInterfaceBody
/ClassOrInterfaceBodyDeclaration
[not(Annotation//Name[ends-with(@Image, 'VisibleForTesting')])]
[
FieldDeclaration[@PackagePrivate='true']
or MethodDeclaration[@PackagePrivate='true']
]
]]>
</value>
</property>
</properties>
</rule>
<rule name="DontImportJavaLang"
since="0.5"
message="Avoid importing anything from the package 'java.lang'"
class="net.sourceforge.pmd.lang.java.rule.codestyle.DontImportJavaLangRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#dontimportjavalang">
<description>
Avoid importing anything from the package 'java.lang'. These classes are automatically imported (JLS 7.5.3).
</description>
<priority>4</priority>
<example>
<![CDATA[
import java.lang.String; // this is unnecessary
public class Foo {}
// --- in another source code file...
import java.lang.*; // this is bad
public class Foo {}
]]>
</example>
</rule>
<rule name="DuplicateImports"
since="0.5"
message="Avoid duplicate imports such as ''{0}''"
class="net.sourceforge.pmd.lang.java.rule.codestyle.DuplicateImportsRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#duplicateimports">
<description>
Duplicate or overlapping import statements should be avoided.
</description>
<priority>4</priority>
<example>
<![CDATA[
import java.lang.String;
import java.lang.*;
public class Foo {}
]]>
</example>
</rule>
<rule name="EmptyMethodInAbstractClassShouldBeAbstract"
language="java"
since="4.1"
class="net.sourceforge.pmd.lang.rule.XPathRule"
message="An empty method in an abstract class should be abstract instead"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#emptymethodinabstractclassshouldbeabstract">
<description>
Empty or auto-generated methods in an abstract class should be tagged as abstract. This helps to remove their inapproprate
usage by developers who should be implementing their own versions in the concrete subclasses.
</description>
<priority>1</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration[@Abstract = 'true']
/ClassOrInterfaceBody
/ClassOrInterfaceBodyDeclaration
/MethodDeclaration[@Abstract = 'false' and @Native = 'false']
[
( boolean(./Block[count(./BlockStatement) = 1]/BlockStatement/Statement/ReturnStatement/Expression/PrimaryExpression/PrimaryPrefix/Literal/NullLiteral) = 'true' )
or
( boolean(./Block[count(./BlockStatement) = 1]/BlockStatement/Statement/ReturnStatement/Expression/PrimaryExpression/PrimaryPrefix/Literal[@Image = '0']) = 'true' )
or
( boolean(./Block[count(./BlockStatement) = 1]/BlockStatement/Statement/ReturnStatement/Expression/PrimaryExpression/PrimaryPrefix/Literal[string-length(@Image) = 2]) = 'true' )
or
(./Block[count(./BlockStatement) = 1]/BlockStatement/Statement/EmptyStatement)
or
( count (./Block/*) = 0 )
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public abstract class ShouldBeAbstract {
public Object couldBeAbstract() {
// Should be abstract method ?
return null;
}
public void couldBeAbstract() {
}
}
]]>
</example>
</rule>
<rule name="ExtendsObject"
language="java"
since="5.0"
message="No need to explicitly extend Object."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#extendsobject">
<description>No need to explicitly extend Object.</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ExtendsList/ClassOrInterfaceType[@Image='Object' or @Image='java.lang.Object']
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo extends Object { // not required
}
]]>
</example>
</rule>
<rule name="FieldDeclarationsShouldBeAtStartOfClass"
language="java"
since="5.0"
message="Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes."
class="net.sourceforge.pmd.lang.java.rule.codestyle.FieldDeclarationsShouldBeAtStartOfClassRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#fielddeclarationsshouldbeatstartofclass">
<description>
Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class HelloWorldBean {
// Field declared before methods / inner classes - OK
private String _thing;
public String getMessage() {
return "Hello World!";
}
// Field declared after methods / inner classes - avoid this
private String _fieldInWrongLocation;
}
]]>
</example>
</rule>
<rule name="FieldNamingConventions"
since="6.7.0"
message="The {0} name ''{1}'' doesn''t match ''{2}''"
class="net.sourceforge.pmd.lang.java.rule.codestyle.FieldNamingConventionsRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#fieldnamingconventions">
<description>
Configurable naming conventions for field declarations. This rule reports variable declarations
which 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_UPPER
convention for constants and enum constants.
</description>
<priority>1</priority>
<example>
<![CDATA[
class Foo {
int myField = 1; // This is in camel case, so it's ok
int my_Field = 1; // This contains an underscore, it's not ok by default
// but you may allow it, or even require the "my_" prefix
final int FinalField = 1; // you may configure a different convention for final fields,
// e.g. here PascalCase: [A-Z][a-zA-Z0-9]*
interface Interface {
double PI = 3.14; // interface "fields" use the constantPattern property
}
enum AnEnum {
ORG, NET, COM; // These use a separate property but are set to ALL_UPPER by default
}
}
]]>
</example>
</rule>
<rule name="ForLoopShouldBeWhileLoop"
language="java"
since="1.02"
message="This for loop could be simplified to a while loop"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#forloopshouldbewhileloop">
<description>
Some for loops can be simplified to while loops, this makes them more concise.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ForStatement
[not(LocalVariableDeclaration)]
[not(ForInit)]
[not(ForUpdate)]
[Expression]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
void bar() {
for (;true;) true; // No Init or Update part, may as well be: while (true)
}
}
]]>
</example>
</rule>
<rule name="ForLoopsMustUseBraces"
language="java"
since="0.7"
deprecated="true"
message="Avoid using 'for' statements without curly braces"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#forloopsmustusebraces">
<description>
Avoid using 'for' statements without using curly braces. If the code formatting or
indentation is lost then it becomes difficult to separate the code being controlled
from the rest.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
by the rule {% rule java/codestyle/ControlStatementBraces %}.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>//ForStatement[not(Statement/Block)]</value>
</property>
</properties>
<example>
<![CDATA[
for (int i = 0; i < 42; i++)
foo();
]]>
</example>
</rule>
<rule name="FormalParameterNamingConventions"
since="6.6.0"
message="The {0} name ''{1}'' doesn''t match ''{2}''"
class="net.sourceforge.pmd.lang.java.rule.codestyle.FormalParameterNamingConventionsRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#formalparameternamingconventions">
<description>
Configurable naming conventions for formal parameters of methods and lambdas.
This rule reports formal parameters which do not match the regex that applies to their
specific kind (e.g. lambda parameter, or final formal parameter). Each regex can be
configured through properties.
By default this rule uses the standard Java naming convention (Camel case).
</description>
<priority>1</priority>
<example>
<![CDATA[
class Foo {
abstract void bar(int myInt); // This is Camel case, so it's ok
void bar(int my_i) { // this will be reported
}
void lambdas() {
// lambdas parameters can be configured separately
Consumer<String> lambda1 = s_str -> { };
// lambda parameters with an explicit type can be configured separately
Consumer<String> lambda1 = (String str) -> { };
}
}
]]>
</example>
</rule>
<rule name="GenericsNaming"
language="java"
since="4.2.6"
message="Generics names should be a one letter long and upper case."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#genericsnaming">
<description>
Names for references to generic values should be limited to a single uppercase letter.
</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//TypeDeclaration/ClassOrInterfaceDeclaration/TypeParameters/TypeParameter[
string-length(@Image) > 1
or
string:upper-case(@Image) != @Image
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public interface GenericDao<E extends BaseModel, K extends Serializable> extends BaseDao {
// This is ok...
}
public interface GenericDao<E extends BaseModel, K extends Serializable> {
// Also this
}
public interface GenericDao<e extends BaseModel, K extends Serializable> {
// 'e' should be an 'E'
}
public interface GenericDao<EF extends BaseModel, K extends Serializable> {
// 'EF' is not ok.
}
]]>
</example>
</rule>
<rule name="IdenticalCatchBranches"
language="java"
since="6.4.0"
minimumLanguageVersion="1.7"
message="''catch'' branch identical to ''{0}'' branch"
class="net.sourceforge.pmd.lang.java.rule.codestyle.IdenticalCatchBranchesRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#identicalcatchbranches">
<description>
Identical `catch` branches use up vertical space and increase the complexity of code without
adding functionality. It's better style to collapse identical branches into a single multi-catch
branch.
</description>
<priority>3</priority>
<example>
<![CDATA[
try {
// do something
} catch (IllegalArgumentException e) {
throw e;
} catch (IllegalStateException e) { // Can be collapsed into the previous block
throw e;
}
try {
// do something
} catch (IllegalArgumentException | IllegalStateException e) { // This is better
throw e;
}
]]>
</example>
</rule>
<rule name="IfElseStmtsMustUseBraces"
language="java"
since="0.2"
deprecated="true"
message="Avoid using 'if...else' statements without curly braces"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#ifelsestmtsmustusebraces">
<description>
Avoid using if..else statements without using surrounding braces. If the code formatting
or indentation is lost then it becomes difficult to separate the code being controlled
from the rest.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
by the rule {% rule java/codestyle/ControlStatementBraces %}.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//Statement
[parent::IfStatement[@Else='true']]
[not(child::Block)]
[not(child::IfStatement)]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
// this is OK
if (foo) x++;
// but this is not
if (foo)
x = x+1;
else
x = x-1;
]]>
</example>
</rule>
<rule name="IfStmtsMustUseBraces"
language="java"
since="1.0"
deprecated="true"
message="Avoid using if statements without curly braces"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#ifstmtsmustusebraces">
<description>
Avoid using if statements without using braces to surround the code block. If the code
formatting or indentation is lost then it becomes difficult to separate the code being
controlled from the rest.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
by the rule {% rule java/codestyle/ControlStatementBraces %}.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//IfStatement[count(*) < 3][not(Statement/Block)]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
if (foo) // not recommended
x++;
if (foo) { // preferred approach
x++;
}
]]>
</example>
</rule>
<rule name="LinguisticNaming"
language="java"
since="6.7.0"
message="Linguistics Antipattern - Method name and return type is inconsistent linguistically"
class="net.sourceforge.pmd.lang.java.rule.codestyle.LinguisticNamingRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#linguisticnaming"
typeResolution="true">
<description>
This rule finds Linguistic Naming Antipatterns. It checks for fields, that are named, as if they should
be boolean but have a different type. It also checks for methods, that according to their name, should
return 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 return
something, 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 are
also transform methods. However, this is disabled by default, since this detection is prone to
false positives.
For more information, see [Linguistic Antipatterns - What They Are and How
Developers Perceive Them](https://doi.org/10.1007/s10664-014-9350-8).
</description>
<priority>3</priority>
<example>
<![CDATA[
public class LinguisticNaming {
int isValid; // the field name indicates a boolean, but it is an int.
boolean isTrue; // correct type of the field
void myMethod() {
int hasMoneyLocal; // the local variable name indicates a boolean, but it is an int.
boolean hasSalaryLocal; // correct naming and type
}
// the name of the method indicates, it is a boolean, but the method returns an int.
int isValid() {
return 1;
}
// correct naming and return type
boolean isSmall() {
return true;
}
// the name indicates, this is a setter, but it returns something
int setName() {
return 1;
}
// the name indicates, this is a getter, but it doesn't return anything
void getName() {
// nothing to return?
}
// the name indicates, it transforms an object and should return the result
void toDataType() {
// nothing to return?
}
// the name indicates, it transforms an object and should return the result
void grapeToWine() {
// nothing to return?
}
}
]]>
</example>
</rule>
<rule name="LocalHomeNamingConvention"
language="java"
since="4.0"
class="net.sourceforge.pmd.lang.rule.XPathRule"
message="The Local Home interface of a Session EJB should be suffixed by 'LocalHome'"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#localhomenamingconvention">
<description>
The Local Home interface of a Session EJB should be suffixed by 'LocalHome'.
</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration
[
(
(./ExtendsList/ClassOrInterfaceType[ends-with(@Image,'EJBLocalHome')])
)
and
not
(
ends-with(@Image,'LocalHome')
)
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public interface MyBeautifulLocalHome extends javax.ejb.EJBLocalHome {} // proper name
public interface MissingProperSuffix extends javax.ejb.EJBLocalHome {} // non-standard name
]]>
</example>
</rule>
<rule name="LocalInterfaceSessionNamingConvention"
language="java"
since="4.0"
class="net.sourceforge.pmd.lang.rule.XPathRule"
message="The Local Interface of a Session EJB should be suffixed by 'Local'"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#localinterfacesessionnamingconvention">
<description>
The Local Interface of a Session EJB should be suffixed by 'Local'.
</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration
[
(
(./ExtendsList/ClassOrInterfaceType[ends-with(@Image,'EJBLocalObject')])
)
and
not
(
ends-with(@Image,'Local')
)
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public interface MyLocal extends javax.ejb.EJBLocalObject {} // proper name
public interface MissingProperSuffix extends javax.ejb.EJBLocalObject {} // non-standard name
]]>
</example>
</rule>
<rule name="LocalVariableCouldBeFinal"
since="2.2"
message="Local variable ''{0}'' could be declared final"
class="net.sourceforge.pmd.lang.java.rule.codestyle.LocalVariableCouldBeFinalRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#localvariablecouldbefinal">
<description>
A local variable assigned only once can be declared final.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class Bar {
public void foo () {
String txtA = "a"; // if txtA will not be assigned again it is better to do this:
final String txtB = "b";
}
}
]]>
</example>
</rule>
<rule name="LocalVariableNamingConventions"
since="6.6.0"
message="The {0} name ''{1}'' doesn''t match ''{2}''"
class="net.sourceforge.pmd.lang.java.rule.codestyle.LocalVariableNamingConventionsRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#localvariablenamingconventions">
<description>
Configurable naming conventions for local variable declarations and other locally-scoped
variables. This rule reports variable declarations which do not match the regex that applies to their
specific kind (e.g. final variable, or catch-clause parameter). Each regex can be configured through
properties.
By default this rule uses the standard Java naming convention (Camel case).
</description>
<priority>1</priority>
<example>
<![CDATA[
class Foo {
void bar() {
int localVariable = 1; // This is in camel case, so it's ok
int local_variable = 1; // This will be reported unless you change the regex
final int i_var = 1; // final local variables can be configured separately
try {
foo();
} catch (IllegalArgumentException e_illegal) {
// exception block parameters can be configured separately
}
}
}
]]>
</example>
</rule>
<rule name="LongVariable"
language="java"
since="0.3"
message="Avoid excessively long variable names like {0}"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#longvariable">
<description>
Fields, formal arguments, or local variable names that are too long can make the code difficult to follow.
</description>
<priority>3</priority>
<properties>
<property name="minimum" type="Integer" description="The variable length reporting threshold" min="1" max="100" value="17"/>
<property name="xpath">
<value>
<![CDATA[
//VariableDeclaratorId[string-length(@Image) > $minimum]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Something {
int reallyLongIntName = -3; // VIOLATION - Field
public static void main( String argumentsList[] ) { // VIOLATION - Formal
int otherReallyLongName = -5; // VIOLATION - Local
for (int interestingIntIndex = 0; // VIOLATION - For
interestingIntIndex < 10;
interestingIntIndex ++ ) {
}
}
]]>
</example>
</rule>
<rule name="MDBAndSessionBeanNamingConvention"
language="java"
since="4.0"
class="net.sourceforge.pmd.lang.rule.XPathRule"
message="SessionBean or MessageBean should be suffixed by Bean"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#mdbandsessionbeannamingconvention">
<description>
The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by 'Bean'.
</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//TypeDeclaration/ClassOrInterfaceDeclaration
[
(
(./ImplementsList/ClassOrInterfaceType[ends-with(@Image,'SessionBean')])
or
(./ImplementsList/ClassOrInterfaceType[ends-with(@Image,'MessageDrivenBean')])
)
and
not
(
ends-with(@Image,'Bean')
)
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class SomeBean implements SessionBean{} // proper name
public class MissingTheProperSuffix implements SessionBean {} // non-standard name
]]>
</example>
</rule>
<rule name="MethodArgumentCouldBeFinal"
since="2.2"
message="Parameter ''{0}'' is not assigned and could be declared final"
class="net.sourceforge.pmd.lang.java.rule.codestyle.MethodArgumentCouldBeFinalRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#methodargumentcouldbefinal">
<description>
A method argument that is never re-assigned within the method can be declared final.
</description>
<priority>3</priority>
<example>
<![CDATA[
public void foo1 (String param) { // do stuff with param never assigning it
}
public void foo2 (final String param) { // better, do stuff with param never assigning it
}
]]>
</example>
</rule>
<rule name="MethodNamingConventions"
since="1.2"
message="The {0} name ''{1}'' doesn''t match ''{2}''"
class="net.sourceforge.pmd.lang.java.rule.codestyle.MethodNamingConventionsRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#methodnamingconventions">
<description>
Configurable naming conventions for method declarations. This rule reports
method declarations which do not match the regex that applies to their
specific kind (e.g. JUnit test or native method). Each regex can be
configured through properties.
By default this rule uses the standard Java naming convention (Camel case).
</description>
<priority>1</priority>
<example>
<![CDATA[
public class Foo {
public void fooStuff() {
}
}
]]>
</example>
</rule>
<rule name="MIsLeadingVariableName"
language="java"
since="3.4"
deprecated="true"
message="Avoid naming non-fields with the prefix 'm_'"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#misleadingvariablename">
<description>
Detects when a non-field has a name starting with 'm_'. This usually denotes a field and could be confusing.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
by the more general rule
{% rule java/codestyle/LocalVariableNamingConventions %}.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//VariableDeclaratorId
[starts-with(@Image, 'm_')]
[not (../../../FieldDeclaration)]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
private int m_foo; // OK
public void bar(String m_baz) { // Bad
int m_boz = 42; // Bad
}
}
]]>
</example>
</rule>
<rule name="NoPackage"
language="java"
since="3.3"
message="All classes and interfaces must belong to a named package"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#nopackage">
<description>
Detects when a class or interface does not have a package definition.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>//ClassOrInterfaceDeclaration[count(preceding::PackageDeclaration) = 0]</value>
</property>
</properties>
<example>
<![CDATA[
// no package declaration
public class ClassInDefaultPackage {
}
]]>
</example>
</rule>
<rule name="UseUnderscoresInNumericLiterals"
language="java"
since="6.10.0"
minimumLanguageVersion="1.7"
message="Number {0} should separate every third digit with an underscore"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#useunderscoresinnumericliterals">
<description>
Since Java 1.7, numeric literals can use underscores to separate digits. This rule enforces that
numeric 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 literals
are not required to have underscores is configurable via a property. Even under that length, underscores
that are misplaced (not making groups of 3 digits) are reported.
</description>
<priority>3</priority>
<properties>
<property name="version" value="2.0"/>
<property name="acceptableDecimalLength" type="Integer" value="4" min="3" max="1000"
description="Length under which literals in base 10 are not required to have underscores"/>
<property name="xpath">
<value>
<![CDATA[
//Literal[
@IntLiteral = true()
or @LongLiteral = true()
or @DoubleLiteral = true()
or @FloatLiteral = true()
]
(: Filter out literals in base other than 10 :)
[not(matches(@Image, "^0[^.]"))]
(: Filter out ignored field name :)
[not(ancestor::VariableDeclarator[1][@Name = 'serialVersionUID'])]
[
some $num in tokenize(@Image, "[.dDfFlLeE+\-]")
satisfies not(
string-length($num) <= $acceptableDecimalLength
and not(contains($num,"_"))
or matches($num, "^[0-9]{1,3}(_[0-9]{3})*$")
)
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
private int num = 1000000; // should be 1_000_000
}
]]>
</example>
</rule>
<rule name="OnlyOneReturn"
since="1.0"
message="A method should have only one exit point, and that should be the last statement in the method"
class="net.sourceforge.pmd.lang.java.rule.codestyle.OnlyOneReturnRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#onlyonereturn">
<description>
A method should have only one exit point, and that should be the last statement in the method.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class OneReturnOnly1 {
public void foo(int x) {
if (x > 0) {
return "hey"; // first exit
}
return "hi"; // second exit
}
}
]]>
</example>
</rule>
<rule name="PackageCase"
language="java"
since="3.3"
message="Package name contains upper case characters"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#packagecase">
<description>
Detects when a package definition contains uppercase characters.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>//PackageDeclaration/Name[lower-case(@Image)!=@Image]</value>
</property>
</properties>
<example>
<![CDATA[
package com.MyCompany; // should be lowercase name
public class SomeClass {
}
]]>
</example>
</rule>
<rule name="PrematureDeclaration"
language="java"
since="5.0"
message="Avoid declaring a variable if it is unreferenced before a possible exit point."
class="net.sourceforge.pmd.lang.java.rule.codestyle.PrematureDeclarationRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#prematuredeclaration">
<description>
Checks for variables that are defined before they might be used. A reference is deemed to be premature if it is created right before a block of code that doesn't use it that also has the ability to return or throw an exception.
</description>
<priority>3</priority>
<example>
<![CDATA[
public int getLength(String[] strings) {
int length = 0; // declared prematurely
if (strings == null || strings.length == 0) return 0;
for (String str : strings) {
length += str.length();
}
return length;
}
]]>
</example>
</rule>
<rule name="RemoteInterfaceNamingConvention"
language="java"
since="4.0"
class="net.sourceforge.pmd.lang.rule.XPathRule"
message="Remote Interface of a Session EJB should NOT be suffixed"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#remoteinterfacenamingconvention">
<description>
Remote Interface of a Session EJB should not have a suffix.
</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration
[
(
(./ExtendsList/ClassOrInterfaceType[ends-with(@Image,'EJBObject')])
)
and
(
ends-with(@Image,'Session')
or
ends-with(@Image,'EJB')
or
ends-with(@Image,'Bean')
)
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
/* Poor Session suffix */
public interface BadSuffixSession extends javax.ejb.EJBObject {}
/* Poor EJB suffix */
public interface BadSuffixEJB extends javax.ejb.EJBObject {}
/* Poor Bean suffix */
public interface BadSuffixBean extends javax.ejb.EJBObject {}
]]>
</example>
</rule>
<rule name="RemoteSessionInterfaceNamingConvention"
language="java"
since="4.0"
class="net.sourceforge.pmd.lang.rule.XPathRule"
message="Remote Home interface of a Session EJB should be suffixed by 'Home'"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#remotesessioninterfacenamingconvention">
<description>
A Remote Home interface type of a Session EJB should be suffixed by 'Home'.
</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration
[
(
(./ExtendsList/ClassOrInterfaceType[ends-with(@Image,'EJBHome')])
)
and
not
(
ends-with(@Image,'Home')
)
]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public interface MyBeautifulHome extends javax.ejb.EJBHome {} // proper name
public interface MissingProperSuffix extends javax.ejb.EJBHome {} // non-standard name
]]>
</example>
</rule>
<rule name="ShortClassName"
language="java"
since="5.0"
message="Avoid short class names like {0}"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#shortclassname">
<description>
Short Classnames with fewer than e.g. five characters are not recommended.
</description>
<priority>4</priority>
<properties>
<property name="minimum" type="Integer" value="5" min="1" max="100" description="Number of characters that are required as a minimum for a class name."/>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration[string-length(@Image) < $minimum]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
}
]]>
</example>
</rule>
<rule name="ShortMethodName"
language="java"
since="0.3"
message="Avoid using short method names"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#shortmethodname">
<description>
Method names that are very short are not helpful to the reader.
</description>
<priority>3</priority>
<properties>
<property name="minimum" type="Integer" value="3" min="1" max="100" description="Number of characters that are required as a minimum for a method name."/>
<property name="xpath">
<value>
<![CDATA[
//MethodDeclarator[string-length(@Image) < $minimum]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class ShortMethod {
public void a( int i ) { // Violation
}
}
]]>
</example>
</rule>
<rule name="ShortVariable"
language="java"
since="0.3"
message="Avoid variables with short names like {0}"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#shortvariable">
<description>
Fields, local variables, or parameter names that are very short are not helpful to the reader.
</description>
<priority>3</priority>
<properties>
<property name="minimum" type="Integer" value="3" min="1" max="100" description="Number of characters that are required as a minimum for a variable name."/>
<property name="version" value="2.0"/>
<property name="xpath">
<value>
<![CDATA[
//VariableDeclaratorId[string-length(@Image) < $minimum]
(: ForStatement :)
[not(../../..[self::ForInit])]
(: Foreach statement :)
[not(../../..[self::ForStatement])]
(: Catch statement parameter :)
[not(../..[self::CatchStatement])]
(: Lambda expression parameter :)
[not(parent::LambdaExpression or ../../..[self::LambdaExpression])]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Something {
private int q = 15; // field - too short
public static void main( String as[] ) { // formal arg - too short
int r = 20 + q; // local var - too short
for (int i = 0; i < 10; i++) { // not a violation (inside 'for' loop)
r += q;
}
for (Integer i : numbers) { // not a violation (inside 'for-each' loop)
r += q;
}
}
}
]]>
</example>
</rule>
<rule name="SuspiciousConstantFieldName"
language="java"
since="2.0"
deprecated="true"
message="The field name indicates a constant but its modifiers do not"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#suspiciousconstantfieldname">
<description>
Field names using all uppercase characters - Sun's Java naming conventions indicating constants - should
be declared as final.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
by the more general rule {% rule java/codestyle/FieldNamingConventions %}.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//ClassOrInterfaceDeclaration[@Interface='false']
/ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/FieldDeclaration
[@Final='false']
[VariableDeclarator/VariableDeclaratorId[upper-case(@Image)=@Image]]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
// this is bad, since someone could accidentally
// do PI = 2.71828; which is actually e
// final double PI = 3.16; is ok
double PI = 3.16;
}
]]>
</example>
</rule>
<rule name="TooManyStaticImports"
language="java"
since="4.1"
class="net.sourceforge.pmd.lang.rule.XPathRule"
message="Too many static imports may lead to messy code"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#toomanystaticimports">
<description>
If you overuse the static import feature, it can make your program unreadable and
unmaintainable, polluting its namespace with all the static members you import.
Readers of your code (including you, a few months after you wrote it) will not know
which class a static member comes from (Sun 1.5 Language Guide).
</description>
<priority>3</priority>
<properties>
<property name="maximumStaticImports" type="Integer"
description="All static imports can be disallowed by setting this to 0" min="0" max="100" value="4"/>
<property name="xpath">
<value>
<![CDATA[
.[count(ImportDeclaration[@Static = 'true']) > $maximumStaticImports]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
import static Lennon;
import static Ringo;
import static George;
import static Paul;
import static Yoko; // Too much !
]]>
</example>
</rule>
<rule name="UnnecessaryAnnotationValueElement"
since="6.2.0"
message="Avoid the use of value in annotations when it's the only element"
class="net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryAnnotationValueElementRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#unnecessaryannotationvalueelement">
<description>
Avoid the use of value in annotations when it's the only element.
</description>
<priority>3</priority>
<example>
<![CDATA[
@TestClassAnnotation(value = "TEST")
public class Foo {
@TestMemberAnnotation(value = "TEST")
private String y;
@TestMethodAnnotation(value = "TEST")
public void bar() {
int x = 42;
return;
}
}
// should be
@TestClassAnnotation("TEST")
public class Foo {
@TestMemberAnnotation("TEST")
private String y;
@TestMethodAnnotation("TEST")
public void bar() {
int x = 42;
return;
}
}
]]>
</example>
</rule>
<rule name="UnnecessaryConstructor"
language="java"
since="1.0"
message="Avoid unnecessary constructors - the compiler will generate these for you"
class="net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryConstructorRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#unnecessaryconstructor">
<description>
This rule detects when a constructor is not necessary; i.e., when there is only one constructor and the
constructor is identical to the default constructor. The default constructor should has same access
modifier as the declaring class. In an enum type, the default constructor is implicitly private.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class Foo {
public Foo() {}
}
]]>
</example>
</rule>
<rule name="UnnecessaryFullyQualifiedName"
language="java"
since="5.0"
class="net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryFullyQualifiedNameRule"
message="Unnecessary use of fully qualified name ''{0}'' due to existing {2}import ''{1}''"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#unnecessaryfullyqualifiedname">
<description>
Import statements allow the use of non-fully qualified names. The use of a fully qualified name
which is covered by an import statement is redundant. Consider using the non-fully qualified name.
</description>
<priority>4</priority>
<example>
<![CDATA[
import java.util.List;
public class Foo {
private java.util.List list1; // Unnecessary FQN
private List list2; // More appropriate given import of 'java.util.List'
}
]]>
</example>
</rule>
<rule name="UnnecessaryLocalBeforeReturn"
since="3.3"
message="Consider simply returning the value vs storing it in local variable ''{0}''"
class="net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryLocalBeforeReturnRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#unnecessarylocalbeforereturn">
<description>
Avoid the creation of unnecessary local variables
</description>
<priority>3</priority>
<example>
<![CDATA[
public class Foo {
public int foo() {
int x = doSomething();
return x; // instead, just 'return doSomething();'
}
}
]]>
</example>
</rule>
<rule name="UnnecessaryModifier"
language="java"
since="1.02"
message="Unnecessary modifier{0} on {1} ''{2}''{3}"
class="net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryModifierRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#unnecessarymodifier">
<description>
Fields in interfaces and annotations are automatically `public static final`, and methods are `public abstract`.
Classes, interfaces or annotations nested in an interface or annotation are automatically `public static`
(all nested interfaces and annotations are automatically static).
Nested enums are automatically `static`.
For historical reasons, modifiers which are implied by the context are accepted by the compiler, but are superfluous.
</description>
<priority>3</priority>
<example>
<![CDATA[
public @interface Annotation {
public abstract void bar(); // both abstract and public are ignored by the compiler
public static final int X = 0; // public, static, and final all ignored
public static class Bar {} // public, static ignored
public static interface Baz {} // ditto
}
public interface Foo {
public abstract void bar(); // both abstract and public are ignored by the compiler
public static final int X = 0; // public, static, and final all ignored
public static class Bar {} // public, static ignored
public static interface Baz {} // ditto
}
public class Bar {
public static interface Baz {} // static ignored
public static enum FoorBar { // static ignored
FOO;
}
}
]]>
</example>
</rule>
<rule name="UnnecessaryReturn"
since="1.3"
message="Avoid unnecessary return statements"
class="net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryReturnRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#unnecessaryreturn">
<description>
Avoid the use of unnecessary return statements.
</description>
<priority>3</priority>
<example>
<![CDATA[
public class Foo {
public void bar() {
int x = 42;
return;
}
}
]]>
</example>
</rule>
<rule name="UseDiamondOperator"
language="java"
since="6.11.0"
message="Explicit type arguments can be replaced by Diamond Operator"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#usediamondoperator"
minimumLanguageVersion="1.7">
<description>
Use the diamond operator to let the type be inferred automatically. With the Diamond operator it is possible
to avoid duplication of the type parameters.
Instead, the compiler is now able to infer the parameter types for constructor calls,
which makes the code also more readable.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//VariableInitializer[preceding-sibling::VariableDeclaratorId[1]/@TypeInferred="false"]
//PrimaryExpression[not(PrimarySuffix)]
[not(ancestor::ArgumentList)]
/PrimaryPrefix/AllocationExpression[ClassOrInterfaceType[@AnonymousClass='false']/TypeArguments//ReferenceType[not(.//TypeArguments)]]
|
//StatementExpression[AssignmentOperator][PrimaryExpression/PrimaryPrefix[not(Expression)]]
//PrimaryExpression[not(PrimarySuffix)]
[not(ancestor::ArgumentList)]
/PrimaryPrefix/AllocationExpression[ClassOrInterfaceType[@AnonymousClass='false']/TypeArguments//ReferenceType[not(.//TypeArguments)]]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
List<String> strings = new ArrayList<String>(); // unnecessary duplication of type parameters
List<String> stringsWithDiamond = new ArrayList<>(); // using the diamond operator is more concise
]]>
</example>
</rule>
<rule name="UselessParentheses"
language="java"
since="5.0"
message="Useless parentheses."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#uselessparentheses">
<description>Useless parentheses should be removed.</description>
<priority>4</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//Expression[not(parent::PrimaryPrefix)]/PrimaryExpression[count(*)>1]
/PrimaryPrefix/Expression
[not(./CastExpression)]
[not(./ConditionalExpression)]
[not(./AdditiveExpression)]
[not(./AssignmentOperator)]
|
//Expression[not(parent::PrimaryPrefix)]/PrimaryExpression[count(*)=1]
/PrimaryPrefix/Expression
|
//Expression/ConditionalAndExpression/PrimaryExpression/PrimaryPrefix/Expression[
count(*)=1 and
count(./CastExpression)=0 and
count(./EqualityExpression/MultiplicativeExpression)=0 and
count(./ConditionalExpression)=0 and
count(./ConditionalOrExpression)=0]
|
//Expression/ConditionalOrExpression/PrimaryExpression/PrimaryPrefix/Expression[
count(*)=1 and
not(./CastExpression) and
not(./ConditionalExpression) and
not(./EqualityExpression/MultiplicativeExpression)]
|
//Expression/ConditionalExpression/PrimaryExpression/PrimaryPrefix/Expression[
count(*)=1 and
not(./CastExpression) and
not(./EqualityExpression)]
|
//Expression/AdditiveExpression[not(./PrimaryExpression/PrimaryPrefix/Literal[@StringLiteral='true'])]
/PrimaryExpression[1]/PrimaryPrefix/Expression[
count(*)=1 and
not(./CastExpression) and
not(./AdditiveExpression[@Image = '-']) and
not(./ShiftExpression) and
not(./RelationalExpression) and
not(./InstanceOfExpression) and
not(./EqualityExpression) and
not(./AndExpression) and
not(./ExclusiveOrExpression) and
not(./InclusiveOrExpression) and
not(./ConditionalAndExpression) and
not(./ConditionalOrExpression) and
not(./ConditionalExpression)]
|
//Expression/EqualityExpression/PrimaryExpression/PrimaryPrefix/Expression[
count(*)=1 and
not(./CastExpression) and
not(./AndExpression) and
not(./InclusiveOrExpression) and
not(./ExclusiveOrExpression) and
not(./ConditionalExpression) and
not(./ConditionalAndExpression) and
not(./ConditionalOrExpression) and
not(./EqualityExpression)]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
private int _bar1;
private Integer _bar2;
public void setBar(int n) {
_bar1 = Integer.valueOf((n)); // here
_bar2 = (n); // and here
}
}
]]>
</example>
</rule>
<rule name="UselessQualifiedThis"
language="java"
since="5.4.0"
message="Useless qualified this usage in the same class."
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#uselessqualifiedthis">
<description>
Reports qualified this usages in the same class.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>
<![CDATA[
//PrimaryExpression
[PrimaryPrefix/Name[@Image]]
[PrimarySuffix[@Arguments='false' and @ArrayDereference = 'false']]
[not(PrimarySuffix/MemberSelector)]
[ancestor::ClassOrInterfaceBodyDeclaration[1][@AnonymousInnerClass='false']]
/PrimaryPrefix/Name[@Image = ancestor::ClassOrInterfaceDeclaration[1]/@Image]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
final Foo otherFoo = Foo.this; // use "this" directly
public void doSomething() {
final Foo anotherFoo = Foo.this; // use "this" directly
}
private ActionListener returnListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doSomethingWithQualifiedThis(Foo.this); // This is fine
}
};
}
private class Foo3 {
final Foo myFoo = Foo.this; // This is fine
}
private class Foo2 {
final Foo2 myFoo2 = Foo2.this; // Use "this" direclty
}
}
]]>
</example>
</rule>
<rule name="VariableNamingConventions"
since="1.2"
deprecated="true"
message="{0} variable {1} should begin with {2}"
class="net.sourceforge.pmd.lang.java.rule.codestyle.VariableNamingConventionsRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#variablenamingconventions">
<description>
A variable naming conventions rule - customize this to your liking. Currently, it
checks for final variables that should be fully capitalized and non-final variables
that should not include underscores.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
by the more general rules {% rule java/codestyle/FieldNamingConventions %},
{% rule java/codestyle/FormalParameterNamingConventions %}, and
{% rule java/codestyle/LocalVariableNamingConventions %}.
</description>
<priority>1</priority>
<example>
<![CDATA[
public class Foo {
public static final int MY_NUM = 0;
public String myTest = "";
DataModule dmTest = new DataModule();
}
]]>
</example>
</rule>
<rule name="WhileLoopsMustUseBraces"
language="java"
since="0.7"
deprecated="true"
message="Avoid using 'while' statements without curly braces"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#whileloopsmustusebraces">
<description>
Avoid using 'while' statements without using braces to surround the code block. If the code
formatting or indentation is lost then it becomes difficult to separate the code being
controlled from the rest.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
by the rule {% rule java/codestyle/ControlStatementBraces %}.
</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value>//WhileStatement[not(Statement/Block)]</value>
</property>
</properties>
<example>
<![CDATA[
while (true) // not recommended
x++;
while (true) { // preferred approach
x++;
}
]]>
</example>
</rule>
</ruleset>