Since: PMD 4.2
Priority: High (1)
If an abstract class does not provide any methods, it may be acting as a simple data containerthat is not meant to be instantiated. In this case, it is probably better to use a private orprotected constructor in order to prevent instantiation than make the class misleadingly abstract.
This rule is defined by the following XPath expression:
//ClassDeclaration[@Abstract=true()and@Interface=false()][ClassBody[not(ConstructorDeclaration|MethodDeclaration)]][not(pmd-java:hasAnnotation('com.google.auto.value.AutoValue')orpmd-java:hasAnnotation('lombok.AllArgsConstructor')orpmd-java:hasAnnotation('lombok.NoArgsConstructor')orpmd-java:hasAnnotation('lombok.RequiredArgsConstructor'))]Example(s):
publicabstractclassExample{Stringfield;intotherField;}Use this rule by referencing it:
<ruleref="category/java/design.xml/AbstractClassWithoutAnyMethod"/>Since: PMD 4.2.6
Priority: Medium (3)
Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block.
This rule is defined by the following XPath expression:
//CatchParameter//ClassType[pmd-java:typeIsExactly('java.lang.NullPointerException')orpmd-java:typeIsExactly('java.lang.Exception')orpmd-java:typeIsExactly('java.lang.RuntimeException')]Example(s):
packagecom.igate.primitive;publicclassPrimitiveType{publicvoiddownCastPrimitiveType(){try{System.out.println(" i ["+i+"]");}catch(Exceptione){e.printStackTrace();}catch(RuntimeExceptione){e.printStackTrace();}catch(NullPointerExceptione){e.printStackTrace();}}}Use this rule by referencing it:
<ruleref="category/java/design.xml/AvoidCatchingGenericException"/>Since: PMD 1.0
Priority: Medium (3)
Avoid creating deeply nested if-then statements since they are harder to read and error-prone to maintain.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.AvoidDeeplyNestedIfStmtsRule
Example(s):
publicclassFoo{publicvoidbar(intx,inty,intz){if(x>y){if(y>z){if(z==x){// !! too deep}}}}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| problemDepth | 3 | The if statement depth reporting threshold |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/AvoidDeeplyNestedIfStmts"/>Use this rule and customize it:
<ruleref="category/java/design.xml/AvoidDeeplyNestedIfStmts"><properties><propertyname="problemDepth"value="3"/></properties></rule>Since: PMD 3.8
Priority: Medium (3)
Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.AvoidRethrowingExceptionRule
Example(s):
publicvoidbar(){try{// do something}catch(SomeExceptionse){throwse;}}Use this rule by referencing it:
<ruleref="category/java/design.xml/AvoidRethrowingException"/>Since: PMD 4.2.5
Priority: Medium (3)
Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same type only add tocode size and runtime complexity.
This rule is defined by the following XPath expression:
//CatchClause[count(Block/*)=1][CatchParameter/ClassType/@SimpleName=Block/ThrowStatement/ConstructorCall/ClassType/@SimpleName][Block/ThrowStatement/ConstructorCall/ArgumentList/@Size=1]/Block/ThrowStatement/ConstructorCallExample(s):
publicvoidbar(){try{// do something}catch(SomeExceptionse){// harmless commentthrownewSomeException(se);}}Use this rule by referencing it:
<ruleref="category/java/design.xml/AvoidThrowingNewInstanceOfSameException"/>Since: PMD 1.8
Priority: High (1)
Avoid throwing NullPointerExceptions manually. These are confusing because most people will assume that thevirtual machine threw it. To avoid a method being called with a null parameter, you may considerusing an IllegalArgumentException instead, making it clearly seen as a programmer-initiated exception.However, there are better ways to handle this:
Effective Java, 3rd Edition, Item 72: Favor the use of standard exceptions
Arguably, every erroneous method invocation boils down to an illegal argument or state,but other exceptions are standardly used for certain kinds of illegal arguments and states.If a caller passes null in some parameter for which null values are prohibited, convention dictates thatNullPointerException be thrown rather than IllegalArgumentException.
To implement that, you are encouraged to usejava.util.Objects.requireNonNull()(introduced in Java 1.7). This method is designed primarily for doing parametervalidation in methods and constructors with multiple parameters.
Your parameter validation could thus look like the following:
public class Foo { private String exampleValue; void setExampleValue(String exampleValue) { // check, throw and assignment in a single standard call this.exampleValue = Objects.requireNonNull(exampleValue, "exampleValue must not be null!"); } }This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.AvoidThrowingNullPointerExceptionRule
Example(s):
publicclassFoo{voidbar(){thrownewNullPointerException();}}Use this rule by referencing it:
<ruleref="category/java/design.xml/AvoidThrowingNullPointerException"/>Since: PMD 1.8
Priority: High (1)
Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable,Exception, or Error, use a subclassed exception or error instead.
This rule is defined by the following XPath expression:
//ThrowStatement//ConstructorCall/ClassType[pmd-java:typeIsExactly('java.lang.Throwable')orpmd-java:typeIsExactly('java.lang.Exception')orpmd-java:typeIsExactly('java.lang.Error')orpmd-java:typeIsExactly('java.lang.RuntimeException')]Example(s):
publicclassFoo{publicvoidbar()throwsException{thrownewException();}}Use this rule by referencing it:
<ruleref="category/java/design.xml/AvoidThrowingRawExceptionTypes"/>Since: PMD 6.13.0
Priority: Medium (3)
Reports unchecked exceptions in thethrows clause of a method or constructor.Java doesn’t force the caller to handle an unchecked exception,so it’s unnecessary except for documentation. A better practice is to document theexceptional cases with a@throws Javadoc tag, which allows being more descriptive.
This rule is defined by the following XPath expression:
//ThrowsList/ClassType[pmd-java:typeIs('java.lang.RuntimeException')]Example(s):
publicvoidfoo()throwsRuntimeException{}Use this rule by referencing it:
<ruleref="category/java/design.xml/AvoidUncheckedExceptionsInSignatures"/>Since: PMD 4.1
Priority: High (1)
Reports classes that may be made final because they cannot be extended from outsidetheir compilation unit anyway. This is because all their constructors are private,so a subclass could not call the super constructor.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.ClassWithOnlyPrivateConstructorsShouldBeFinalRule
Example(s):
publicclassFoo{//Should be finalprivateFoo(){}}Use this rule by referencing it:
<ruleref="category/java/design.xml/ClassWithOnlyPrivateConstructorsShouldBeFinal"/>Since: PMD 6.35.0
Priority: Medium (3)
Methods that are highly complex are difficult to read and more costly to maintain. If you include too much decisionallogic within a single method, you make its behavior hard to understand and more difficult to modify.
Cognitive complexity is a measure of how difficult it is for humans to read and understand a method. Code that containsa break in the control flow is more complex, whereas the use of language shorthands doesn’t increase the level ofcomplexity. Nested control flows can make a method more difficult to understand, with each additional nesting of thecontrol flow leading to an increase in cognitive complexity.
Information about Cognitive complexity can be found in the original paper here:https://www.sonarsource.com/docs/CognitiveComplexity.pdf
By default, this rule reports methods with a complexity of 15 or more. Reported methods should be broken down into lesscomplex components.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.CognitiveComplexityRule
Example(s):
publicclassFoo{// Has a cognitive complexity of 0publicvoidcreateAccount(){Accountaccount=newAccount("PMD");// save account}// Has a cognitive complexity of 1publicBooleansetPhoneNumberIfNotExisting(Accounta,Stringphone){if(a.phone==null){// +1a.phone=phone;returntrue;}returnfalse;}// Has a cognitive complexity of 4publicvoidupdateContacts(List<Contact>contacts){List<Contact>contactsToUpdate=newArrayList<Contact>();for(Contactcontact:contacts){// +1if(contact.department.equals("Finance")){// +2 (nesting = 1)contact.title="Finance Specialist";contactsToUpdate.add(contact);}elseif(contact.department.equals("Sales")){// +1contact.title="Sales Specialist";contactsToUpdate.add(contact);}}// save contacts}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| reportLevel | 15 | Cognitive Complexity reporting threshold |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/CognitiveComplexity"/>Use this rule and customize it:
<ruleref="category/java/design.xml/CognitiveComplexity"><properties><propertyname="reportLevel"value="15"/></properties></rule>Since: PMD 3.1
Priority: Medium (3)
Reports nested ‘if’ statements that can be merged together by joining theirconditions with a boolean&& operator in between.
This rule is defined by the following XPath expression:
//IfStatement[@Else=false()]/IfStatement[@Else=false()]|//IfStatement[@Else=false()]/Block[count(*)=1]/IfStatement[@Else=false()]Example(s):
classFoo{voidbar(){if(x){// original implementationif(y){// do stuff}}}voidbar(){if(x&&y){// clearer implementation// do stuff}}}Use this rule by referencing it:
<ruleref="category/java/design.xml/CollapsibleIfStatements"/>Since: PMD 1.04
Priority: Medium (3)
This rule counts the number of unique attributes, local variables, and return types within an object.A number higher than the specified threshold can indicate a high degree of coupling.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.CouplingBetweenObjectsRule
Example(s):
importcom.Blah;importorg.Bar;importorg.Bardo;publicclassFoo{privateBlahvar1;privateBarvar2;//followed by many imports of unique objectsObjectCdoWork(){Bardovar55;ObjectAvar44;ObjectZvar93;returnsomething();}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| threshold | 20 | Unique type reporting threshold |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/CouplingBetweenObjects"/>Use this rule and customize it:
<ruleref="category/java/design.xml/CouplingBetweenObjects"><properties><propertyname="threshold"value="20"/></properties></rule>Since: PMD 1.03
Priority: Medium (3)
The complexity of methods directly affects maintenance costs and readability. Concentrating too much decisional logicin a single method makes its behaviour hard to read and change.
Cyclomatic complexity assesses the complexity of a method by counting the number of decision points in a method,plus one for the method entry. Decision points are places where the control flow jumps to another place in theprogram. As such, they include all control flow statements, such asif,while,for, andcase. For moredetails on the calculation, see the documentationCYCLO.
Generally, numbers ranging from 1-4 denote low complexity, 5-7 denote moderate complexity, 8-10 denotehigh complexity, and 11+ is very high complexity. By default, this rule reports methods with a complexity >= 10.Additionally, classes with many methods of moderate complexity get reported as well once the total of theirmethods’ complexities reaches 80, even if none of the methods was directly reported.
Reported methods should be broken down into several smaller methods. Reported classes should probably be broken downinto subcomponents.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.CyclomaticComplexityRule
Example(s):
classFoo{voidbaseCyclo(){// Cyclo = 1highCyclo();}voidhighCyclo(){// Cyclo = 10: reported!intx=0,y=2;booleana=false,b=true;if(a&&(y==1?b:true)){// +3if(y==x){// +1while(true){// +1if(x++<20){// +1break;// +1}}}elseif(y==t&&!d){// +2x=a?y:x;// +1}else{x=2;}}}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| classReportLevel | 80 | Total class complexity reporting threshold |
| methodReportLevel | 10 | Cyclomatic complexity reporting threshold |
| cycloOptions | Choose options for the computation of Cyclo |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/CyclomaticComplexity"/>Use this rule and customize it:
<ruleref="category/java/design.xml/CyclomaticComplexity"><properties><propertyname="classReportLevel"value="80"/><propertyname="methodReportLevel"value="10"/><propertyname="cycloOptions"value=""/></properties></rule>Since: PMD 6.0.0
Priority: Medium (3)
Data Classes are simple data holders, which reveal most of their state, andwithout complex functionality. The lack of functionality may indicate thattheir behaviour is defined elsewhere, which is a sign of poor data-behaviourproximity. By directly exposing their internals, Data Classes break encapsulation,and therefore reduce the system’s maintainability and understandability. Moreover,classes tend to strongly rely on their data representation, which makes for a brittledesign.
Refactoring a Data Class should focus on restoring a good data-behaviour proximity. Inmost cases, that means moving the operations defined on the data back into the class.In some other cases it may make sense to remove entirely the class and move the datainto the former client classes.
The rule uses metrics to implement its detection strategy. The violation messagegives information about the values of these metrics:
WEIGHED_METHOD_COUNTWEIGHT_OF_CLASSNUMBER_OF_PUBLIC_FIELDSNUMBER_OF_ACCESSORSThe rule identifies a god class by looking for classes which have all of the following properties:
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.DataClassRule
Example(s):
publicclassDataClass{// class exposes public attributespublicStringname="";publicintbar=0;publicintna=0;privateintbee=0;// and private ones through getterspublicvoidsetBee(intn){bee=n;}}Use this rule by referencing it:
<ruleref="category/java/design.xml/DataClass"/>Since: PMD 4.0
Priority: Medium (3)
Errors are system exceptions. Do not extend them.
This rule is defined by the following XPath expression:
//ClassDeclaration/ExtendsList/ClassType[pmd-java:typeIs('java.lang.Error')]Example(s):
publicclassFooextendsError{}Use this rule by referencing it:
<ruleref="category/java/design.xml/DoNotExtendJavaLangError"/>Since: PMD 1.8
Priority: Medium (3)
This rule reports exceptions thrown and caught in an enclosing try statement.This use of exceptions as a form ofgoto statement is discouraged, as that mayhide actual exceptions, and obscures control flow, especially when debugging.To fix a violation, add the necessary validation or use an alternate control structure.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.ExceptionAsFlowControlRule
Example(s):
publicvoidbar(){try{try{}catch(Exceptione){thrownewWrapperException(e);// this is essentially a GOTO to the WrapperException catch block}}catch(WrapperExceptione){// do some more stuff}}Use this rule by referencing it:
<ruleref="category/java/design.xml/ExceptionAsFlowControl"/>Since: PMD 1.04
Priority: Medium (3)
A high number of imports can indicate a high degree of coupling within an object. This rulecounts the number of unique imports and reports a violation if the count is above theuser-specified threshold.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.ExcessiveImportsRule
Example(s):
importblah.blah.Baz;importblah.blah.Bif;// 28 others from the same package elidedpublicclassFoo{publicvoiddoWork(){}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| minimum | 30 | Threshold above which a node is reported |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/ExcessiveImports"/>Use this rule and customize it:
<ruleref="category/java/design.xml/ExcessiveImports"><properties><propertyname="minimum"value="30"/></properties></rule>Since: PMD 0.9
Priority: Medium (3)
Methods with numerous parameters are a challenge to maintain, especially if most of them share thesame datatype. These situations usually denote the need for new objects to wrap the numerous parameters.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.ExcessiveParameterListRule
Example(s):
publicvoidaddPerson(// too many arguments liable to be mixed upintbirthYear,intbirthMonth,intbirthDate,intheight,intweight,intssn){....}publicvoidaddPerson(// preferred approachDatebirthdate,BodyMeasurementsmeasurements,intssn){....}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| minimum | 10 | Threshold above which a node is reported |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/ExcessiveParameterList"/>Use this rule and customize it:
<ruleref="category/java/design.xml/ExcessiveParameterList"><properties><propertyname="minimum"value="10"/></properties></rule>Since: PMD 1.04
Priority: Medium (3)
Classes with large numbers of public methods and attributes require disproportionate testing effortssince combinational side effects grow rapidly and increase risk. Refactoring these classes intosmaller ones not only increases testability and reliability but also allows new variations to bedeveloped easily.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.ExcessivePublicCountRule
Example(s):
publicclassFoo{publicStringvalue;publicBarsomething;publicVariablevar;// [... more more public attributes ...]publicvoiddoWork(){}publicvoiddoMoreWork(){}publicvoiddoWorkAgain(){}// [... more more public methods ...]}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| minimum | 45 | Threshold above which a node is reported |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/ExcessivePublicCount"/>Use this rule and customize it:
<ruleref="category/java/design.xml/ExcessivePublicCount"><properties><propertyname="minimum"value="45"/></properties></rule>Since: PMD 1.1
Priority: Medium (3)
If a final field is assigned to a compile-time constant, it could be made static, thus saving overheadin each object at runtime.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.FinalFieldCouldBeStaticRule
Example(s):
publicclassFoo{publicfinalintBAR=42;// this could be static and save some space}Use this rule by referencing it:
<ruleref="category/java/design.xml/FinalFieldCouldBeStatic"/>Since: PMD 5.0
Priority: Medium (3)
The God Class rule detects the God Class design flaw using metrics. God classes do too many things,are very big and overly complex. They should be split apart to be more object-oriented.The rule uses the detection strategy described in "Object-Oriented Metrics in Practice".The violations are reported against the entire class.
The rule uses metrics to implement its detection strategy. The violation messagegives information about the values of these metrics:
WEIGHED_METHOD_COUNTACCESS_TO_FOREIGN_DATATIGHT_CLASS_COHESIONThe rule identifies a god class by looking for classes which have all of the following properties:
See also the reference:
Michele Lanza and Radu Marinescu.Object-Oriented Metrics in Practice:Using Software Metrics to Characterize, Evaluate, and Improve the Designof Object-Oriented Systems. Springer, Berlin, 1 edition, October 2006. Page 80.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.GodClassRule
Use this rule by referencing it:
<ruleref="category/java/design.xml/GodClass"/>Since: PMD 2.0
Priority: Medium (3)
Reports non-final fields whose value never changes once object initialization ends,and hence may be marked final.
Note that this rule does not enforce that the field value be deeply immutable itself.An object can still have mutable state, even if all its member fields are declared final.This is referred to as shallow immutability. For more information on mutability,seeEffective Java, 3rd Edition, Item 17: Minimize mutability.
Limitations: We can only check private fields for now.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.ImmutableFieldRule
Example(s):
publicclassFoo{privateintx;// could be finalpublicFoo(){x=7;}publicvoidfoo(){inta=x+2;}}Use this rule by referencing it:
<ruleref="category/java/design.xml/ImmutableField"/>Since: PMD 6.52.0
Priority: Medium (3)
Identifies beans, that don’t follow theJavaBeans API specification.
Each non-static field should have both a getter and a setter method. If the field is just used internally and is nota bean property, then the field should be marked astransient.
The rule verifies that the type of the field is the same as the result type of the getter. And that this type matchesthe type used in the setter.
The rule also checks, that there is a no-arg or default constructor available.
Optionally the rule also verifies, that the bean implementsjava.io.Serializable. While this is a requirement for theoriginal JavaBeans specification, frameworks nowadays don’t strictly require this anymore.
In order to avoid many false positives in classes that are not beans, the rule needs to be explicitlyenabled by configuring the propertypackages.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.InvalidJavaBeanRule
Example(s):
packageorg.example.beans;publicclassMyBean{// <-- bean is not serializable, missing "implements Serializable"privateStringlabel;// <-- missing setter for property "label"publicStringgetLabel(){returnlabel;}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ensureSerialization | false | Require that beans implement java.io.Serializable. |
| packages | org.example.beans | Consider classes in only these package to be beans. Set to an empty value to check all classes. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/InvalidJavaBean"/>Use this rule and customize it:
<ruleref="category/java/design.xml/InvalidJavaBean"><properties><propertyname="ensureSerialization"value="false"/><propertyname="packages"value="org.example.beans"/></properties></rule>Since: PMD 5.0
Priority: Medium (3)
The law of Demeter is a simple rule that says "only talk to friends". It forbidsfetching data from "too far away", for some definition of distance, in order toreduce coupling between classes or objects of different levels of abstraction.
The rule uses a notion of "degree", that quantifies how "far" an object is.Expressions with too high degree can only be used in certain ways. The degree ofan expression is defined inductively:
this is 0expr.field is the degree ofexpr plus 1expr.getFoo() is the degree ofexpr plus 1expr.withFoo("") is the degree ofexprIntuitively, the more you call getters, the more the degree increases. Eventuallythe degree reaches the report threshold (propertytrustRadius) and the expressionis reported. The details of the calculation are more involved and make room for commonpatterns, like usage of collections (objects that are in a list or array have thesame degree as their container), the builder pattern, and getters that do not appearto break a boundary of abstraction.
Be aware that this rule is prone to many false-positives and low-priority warnings.You can increase thetrustRadius property to reduce them drastically. The defaulttrustRadius of 1 corresponds to the original law of Demeter (you’re only allowedone getter call on untrusted values). Given sometrustRadius value:
trustRadius are not reportedtrustRadius + 1 are reported, unless they are only returnedfrom the current method, or passed as argument to another method. Without this exception itwould not be possible to extract any information from e.g. method parameters.trustRadius + 1 are not reported. Theintuition is that to obtain a value of degreen > 1 then you must use an expressionof degreen - 1, so if you haven > trustRadius + 1, there you’re using some valueof degreetrustRadius + 1 that will be reported.See also the references:
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.LawOfDemeterRule
Example(s):
publicclassFoo{/** * This example will result in one violation. */publicvoidexample(Barb){// b has degree 1// `b.getC()` has degree 2, it's breaking a boundary of abstraction and so is reported.b.getC().doIt();// To respect the law of Demeter, Bar should encapsulate its// C member more properly, eg by exposing a method like this:b.callDoItOnC();// a constructor call, not a method call.Dd=newD();// this method call is ok, because we have create the new// instance of D locally.d.doSomethingElse();}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| trustRadius | 1 | Maximum degree of trusted data. The default of 1 is the most restrictive. |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/LawOfDemeter"/>Use this rule and customize it:
<ruleref="category/java/design.xml/LawOfDemeter"><properties><propertyname="trustRadius"value="1"/></properties></rule>Since: PMD 5.0
Priority: Medium (3)
Use opposite operator instead of negating the whole expression with a logic complement operator.
This rule is defined by the following XPath expression:
//UnaryExpression[@Operator='!']/InfixExpression[@Operator=('==','!=','<','>','<=','>=')]Example(s):
publicbooleanbar(inta,intb){if(!(a==b)){// use !=returnfalse;}if(!(a<b)){// use >=returnfalse;}returntrue;}Use this rule by referencing it:
<ruleref="category/java/design.xml/LogicInversion"/>Since: PMD 5.0
Priority: Medium (3)
Avoid using classes from the configured package hierarchy outside of the package hierarchy,except when using one of the configured allowed classes.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.LoosePackageCouplingRule
Example(s):
packagesome.package;importsome.other.package.subpackage.subsubpackage.DontUseThisClass;publicclassBar{DontUseThisClassboo=newDontUseThisClass();}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| packages | Restricted packages | |
| classes | Allowed classes |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/LoosePackageCoupling"/>Use this rule and customize it:
<ruleref="category/java/design.xml/LoosePackageCoupling"><properties><propertyname="packages"value=""/><propertyname="classes"value=""/></properties></rule>Since: PMD 6.35.0
Priority: Medium (3)
Non-private static fields should be made constants (or immutable references) bydeclaring them final.
Non-private non-final static fields break encapsulation and can lead to hard to findbugs, since these fields can be modified from anywhere within the program.Callers can trivially access and modify non-private non-final static fields. Neitheraccesses nor modifications can be guarded against, and newly set values cannotbe validated.
If you are using this rule, then you don’t need thisruleAssignmentToNonFinalStatic.
This rule is defined by the following XPath expression:
//FieldDeclaration[pmd-java:modifiers()="static"][not(pmd-java:modifiers()=("private","final"))]Example(s):
publicclassGreeter{publicstaticFoofoo=newFoo();...}// avoid thispublicclassGreeter{publicstaticfinalFooFOO=newFoo();...}// use this insteadUse this rule by referencing it:
<ruleref="category/java/design.xml/MutableStaticState"/>Since: PMD 6.0.0
Priority: Medium (3)
This rule uses the NCSS (Non-Commenting Source Statements) metric to determine the number of linesof code in a class, method or constructor. NCSS ignores comments, blank lines, and only counts actualstatements. For more details on the calculation, see the documentationNCSS.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.NcssCountRule
Example(s):
importjava.util.Collections;// +0importjava.io.IOException;// +0classFoo{// +1, total Ncss = 12publicvoidbigMethod()// +1throwsIOException{intx=0,y=2;// +1booleana=false,b=true;// +1if(a||b){// +1try{// +1do{// +1x+=2;// +1}while(x<12);System.exit(0);// +1}catch(IOExceptionioe){// +1thrownewPatheticFailException(ioe);// +1}}else{assertfalse;// +1}}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| methodReportLevel | 60 | NCSS reporting threshold for methods |
| classReportLevel | 1500 | NCSS reporting threshold for classes |
| ncssOptions | Choose options for the computation of Ncss |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/NcssCount"/>Use this rule and customize it:
<ruleref="category/java/design.xml/NcssCount"><properties><propertyname="methodReportLevel"value="60"/><propertyname="classReportLevel"value="1500"/><propertyname="ncssOptions"value=""/></properties></rule>Since: PMD 3.9
Priority: Medium (3)
The NPath complexity of a method is the number of acyclic execution paths through that method.While cyclomatic complexity counts the number of decision points in a method, NPath counts the number offull paths from the beginning to the end of the block of the method. That metric grows exponentially, asit multiplies the complexity of statements in the same block. For more details on the calculation, see thedocumentationNPATH.
A threshold of 200 is generally considered the point where measures should be taken to reducecomplexity and increase readability.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.NPathComplexityRule
Example(s):
publicclassFoo{publicstaticvoidbar(){// Ncss = 252: reported!booleana,b=true;try{// 2 * 2 + 2 = 6if(true){// 2Listbuz=newArrayList();}for(inti=0;i<19;i++){// * 2Listbuz=newArrayList();}}catch(Exceptione){if(true){// 2e.printStackTrace();}}while(j++<20){// * 2Listbuz=newArrayList();}switch(j){// * 7case1:case2:break;case3:j=5;break;case4:if(b&&a){bar();}break;default:break;}do{// * 3Listbuz=newArrayList();}while(a&&j++<30);}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| reportLevel | 200 | N-Path Complexity reporting threshold |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/NPathComplexity"/>Use this rule and customize it:
<ruleref="category/java/design.xml/NPathComplexity"><properties><propertyname="reportLevel"value="200"/></properties></rule>Since: PMD 1.2
Priority: Medium (3)
A method/constructor shouldn’t explicitly throw the generic java.lang.Exception, since itis unclear which exceptions that can be thrown from the methods. It might bedifficult to document and understand such vague interfaces. Use either a classderived from RuntimeException or a checked exception.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.SignatureDeclareThrowsExceptionRule
Example(s):
publicvoidfoo()throwsException{}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| IgnoreJUnitCompletely | false | Allow all methods in a JUnit3 TestCase to throw Exceptions |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/SignatureDeclareThrowsException"/>Use this rule and customize it:
<ruleref="category/java/design.xml/SignatureDeclareThrowsException"><properties><propertyname="IgnoreJUnitCompletely"value="false"/></properties></rule>Since: PMD 5.4.0
Priority: Medium (3)
Reports ternary expression with the formcondition ? literalBoolean : fooorcondition ? foo : literalBoolean.
These expressions can be simplified as follows:
condition ? true : expr simplifies tocondition || exprcondition ? false : expr simplifies to!condition && exprcondition ? expr : true simplifies to!condition || exprcondition ? expr : false simplifies tocondition && exprThis rule is defined by the following XPath expression:
//ConditionalExpression[BooleanLiteralandnot(NullLiteral)]Example(s):
publicclassFoo{publicbooleantest(){returncondition?true:something();// can be as simple as return condition || something();}publicvoidtest2(){finalbooleanvalue=condition?false:something();// can be as simple as value = !condition && something();}publicbooleantest3(){returncondition?something():true;// can be as simple as return !condition || something();}publicvoidtest4(){finalbooleanotherValue=condition?something():false;// can be as simple as condition && something();}publicbooleantest5(){returncondition?true:false;// can be as simple as return condition;}}Use this rule by referencing it:
<ruleref="category/java/design.xml/SimplifiedTernary"/>Since: PMD 1.05
Priority: Medium (3)
Avoid unnecessary comparisons in boolean expressions, they serve no purpose and impacts readability.
This rule is defined by the following XPath expression:
//InfixExpression[@Operator=("==","!=")]/BooleanLiteralExample(s):
publicclassBar{// can be simplified to// bar = isFoo();privatebooleanbar=(isFoo()==true);publicisFoo(){returnfalse;}}Use this rule by referencing it:
<ruleref="category/java/design.xml/SimplifyBooleanExpressions"/>Since: PMD 0.9
Priority: Medium (3)
Avoid unnecessary if-then-else statements when returning a boolean. The result ofthe conditional test can be returned instead.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.SimplifyBooleanReturnsRule
Example(s):
publicbooleanisBarEqualTo(intx){if(bar==x){// this bit of code...returntrue;}else{returnfalse;}}publicbooleanisBarEqualTo(intx){returnbar==x;// can be replaced with this}Use this rule by referencing it:
<ruleref="category/java/design.xml/SimplifyBooleanReturns"/>Since: PMD 3.1
Priority: Medium (3)
No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.SimplifyConditionalRule
Example(s):
classFoo{voidbar(Objectx){if(x!=null&&xinstanceofBar){// just drop the "x != null" check}}}Use this rule by referencing it:
<ruleref="category/java/design.xml/SimplifyConditional"/>Since: PMD 3.1
Priority: Medium (3)
Reports fields which may be converted to a local variable. This is so becausein every method where the field is used, it is assigned before it is first read.Hence, the value that the field had before the method call may not be observed,so it might as well not be stored in the enclosing object.
Limitations:
ignoredAnnotations property).This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.SingularFieldRule
Example(s):
publicclassFoo{privateintx;// this will be reportedpublicintfoo(inty){x=y+5;// assigned before any readreturnx;}publicintfooOk(inty){intz=y+5;// might as well be a local like herereturnz;}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoredAnnotations | java.lang.Deprecated , javafx.fxml.FXML , lombok.Getter , lombok.Setter , lombok.experimental.Delegate | 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/design.xml/SingularField"/>Use this rule and customize it:
<ruleref="category/java/design.xml/SingularField"><properties><propertyname="ignoredAnnotations"value="java.lang.Deprecated,javafx.fxml.FXML,lombok.Getter,lombok.Setter,lombok.experimental.Delegate"/></properties></rule>Since: PMD 1.02
Priority: Medium (3)
A high ratio of statements to labels in a switch statement implies that the switch statementis overloaded. Consider moving the statements into new methods or creating subclasses basedon the switch variable.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.SwitchDensityRule
Example(s):
publicclassFoo{publicvoidbar(intx){switch(x){case1:{// lots of statementsbreak;}case2:{// lots of statementsbreak;}}}}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| minimum | 10 | Threshold above which a switch statement or expression is reported |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/SwitchDensity"/>Use this rule and customize it:
<ruleref="category/java/design.xml/SwitchDensity"><properties><propertyname="minimum"value="10"/></properties></rule>Since: PMD 3.0
Priority: Medium (3)
Classes that have too many fields can become unwieldy and could be redesigned to have fewer fields,possibly through grouping related fields in new objects. For example, a class with individualcity/state/zip fields could park them within a single Address field.
This rule is defined by the following XPath expression:
//ClassDeclaration/ClassBody[count(FieldDeclaration[not(pmd-java:modifiers()='final')][not(pmd-java:modifiers()='static')])>$maxfields]Example(s):
publicclassPerson{// too many separate fieldsintbirthYear;intbirthMonth;intbirthDate;floatheight;floatweight;}publicclassPerson{// this is more manageableDatebirthDate;BodyMeasurementsmeasurements;}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| maxfields | 15 | Max allowable fields |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/TooManyFields"/>Use this rule and customize it:
<ruleref="category/java/design.xml/TooManyFields"><properties><propertyname="maxfields"value="15"/></properties></rule>Since: PMD 4.2
Priority: Medium (3)
A class with too many methods is probably a good suspect for refactoring, in order to reduce itscomplexity and find a way to have more fine grained objects.
This rule is defined by the following XPath expression:
//ClassDeclaration/ClassBody[count(MethodDeclaration[not((starts-with(@Name,'get')orstarts-with(@Name,'set')orstarts-with(@Name,'is'))andcount(Block/*)<=1)])>$maxmethods]This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| maxmethods | 10 | The method count reporting threshold |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/TooManyMethods"/>Use this rule and customize it:
<ruleref="category/java/design.xml/TooManyMethods"><properties><propertyname="maxmethods"value="10"/></properties></rule>Since: PMD 3.3
Priority: Medium (3)
The overriding method merely calls the same method defined in a superclass.
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.UselessOverridingMethodRule
Example(s):
publicvoidfoo(Stringbar){super.foo(bar);// why bother overriding?}publicStringfoo(){returnsuper.foo();// why bother overriding?}@IdpublicLonggetId(){returnsuper.getId();// OK if 'ignoreAnnotations' is false, which is the default behavior}This rule has the following properties:
| Name | Default Value | Description |
|---|---|---|
| ignoreAnnotations | false | Ignore methods that have annotations (except @Override) |
Use this rule with the default properties by just referencing it:
<ruleref="category/java/design.xml/UselessOverridingMethod"/>Use this rule and customize it:
<ruleref="category/java/design.xml/UselessOverridingMethod"><properties><propertyname="ignoreAnnotations"value="false"/></properties></rule>Since: PMD 4.2.6
Priority: Medium (3)
When you write a public method, you should be thinking in terms of an API. If your method is public, it means other classwill use it, therefore, you want (or need) to offer a comprehensive and evolutive API. If you pass a lot of informationas a simple series of Strings, you may think of using an Object to represent all those information. You’ll get a simplerAPI (such as doWork(Workload workload), rather than a tedious series of Strings) and more importantly, if you need at somepoint to pass extra data, you’ll be able to do so by simply modifying or extending Workload without any modification toyour API.
This rule is defined by the following XPath expression:
//MethodDeclaration[pmd-java:modifiers()='public'][count(FormalParameters/FormalParameter[pmd-java:typeIs('java.lang.String')])>3]Example(s):
publicclassMyClass{publicvoidconnect(Stringusername,Stringpssd,StringdatabaseName,StringdatabaseAddress)// Instead of those parameters object// would ensure a cleaner API and permit// to add extra data transparently (no code change):// void connect(UserData data);{}}Use this rule by referencing it:
<ruleref="category/java/design.xml/UseObjectForClearerAPI"/>Since: PMD 0.3
Priority: Medium (3)
For classes that only have static methods, consider making them utility classes.Note that this doesn’t apply to abstract classes, since their subclasses maywell include non-static methods. Also, if you want this class to be a utility class,remember to add a private constructor to prevent instantiation.(Note, that this use was known before PMD 5.1.0 as UseSingleton).
This rule is defined by the following Java class:net.sourceforge.pmd.lang.java.rule.design.UseUtilityClassRule
Example(s):
publicclassMaybeAUtility{publicstaticvoidfoo(){}publicstaticvoidbar(){}}Use this rule by referencing it:
<ruleref="category/java/design.xml/UseUtilityClass"/>