UNPKG

@aire-ux/aire-switch

Version:
1,408 lines (1,331 loc) 123 kB
<?xml version="1.0"?> <ruleset name="Error Prone" 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 to detect constructs that are either broken, extremely confusing or prone to runtime errors. </description> <rule name="AssignmentInOperand" language="java" since="1.03" message="Avoid assignments in operands" class="net.sourceforge.pmd.lang.java.rule.errorprone.AssignmentInOperandRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#assignmentinoperand"> <description> Avoid assignments in operands; this can make code more complicated and harder to read. </description> <priority>3</priority> <example> <![CDATA[ public void bar() { int x = 2; if ((x = getX()) == 3) { System.out.println("3!"); } } ]]> </example> </rule> <rule name="AssignmentToNonFinalStatic" language="java" since="2.2" message="Possible unsafe assignment to a non-final static field in a constructor." class="net.sourceforge.pmd.lang.java.rule.errorprone.AssignmentToNonFinalStaticRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#assignmenttononfinalstatic"> <description> Identifies a possible unsafe usage of a static field. </description> <priority>3</priority> <example> <![CDATA[ public class StaticField { static int x; public FinalFields(int y) { x = y; // unsafe } } ]]> </example> </rule> <rule name="AvoidAccessibilityAlteration" language="java" since="4.1" message="You should not modify visibility of class or methods using getDeclaredConstructors(), getDeclaredConstructor(Class[]), setAccessible() or PrivilegedAction." class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidaccessibilityalteration"> <description> Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface PrivilegedAction, allow for the runtime alteration of variable, class, or method visibility, even if they are private. This violates the principle of encapsulation. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //PrimaryExpression[ ( (PrimarySuffix[ ends-with(@Image,'getDeclaredConstructors') or ends-with(@Image,'getDeclaredConstructor') or ends-with(@Image,'setAccessible') ]) or (PrimaryPrefix/Name[ ends-with(@Image,'getDeclaredConstructor') or ends-with(@Image,'getDeclaredConstructors') or starts-with(@Image,'AccessibleObject.setAccessible') ]) ) and (//ImportDeclaration/Name[ contains(@Image,'java.security.PrivilegedAction')]) ] ]]> </value> </property> </properties> <example> <![CDATA[ import java.lang.reflect.AccessibleObject; import java.lang.reflect.Method; import java.security.PrivilegedAction; public class Violation { public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException { // Possible call to forbidden getDeclaredConstructors Class[] arrayOfClass = new Class[1]; this.getClass().getDeclaredConstructors(); this.getClass().getDeclaredConstructor(arrayOfClass); Class clazz = this.getClass(); clazz.getDeclaredConstructor(arrayOfClass); clazz.getDeclaredConstructors(); // Possible call to forbidden setAccessible clazz.getMethod("", arrayOfClass).setAccessible(false); AccessibleObject.setAccessible(null, false); Method.setAccessible(null, false); Method[] methodsArray = clazz.getMethods(); int nbMethod; for ( nbMethod = 0; nbMethod < methodsArray.length; nbMethod++ ) { methodsArray[nbMethod].setAccessible(false); } // Possible call to forbidden PrivilegedAction PrivilegedAction priv = (PrivilegedAction) new Object(); priv.run(); } } ]]> </example> </rule> <rule name="AvoidAssertAsIdentifier" language="java" since="3.4" message="Avoid using assert as an identifier; it became a reserved word in JDK 1.4" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidassertasidentifier"> <description> Use of the term 'assert' will conflict with newer versions of Java since it is a reserved word. </description> <priority>2</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value>//VariableDeclaratorId[@Name='assert']</value> </property> </properties> <example> <![CDATA[ public class A { public class Foo { String assert = "foo"; } } ]]> </example> </rule> <rule name="AvoidBranchingStatementAsLastInLoop" language="java" since="5.0" class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidBranchingStatementAsLastInLoopRule" message="Avoid using a branching statement as the last in a loop." externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidbranchingstatementaslastinloop"> <description> Using a branching statement as the last part of a loop may be a bug, and/or is confusing. Ensure that the usage is not a bug, or consider using another approach. </description> <priority>2</priority> <example> <![CDATA[ // unusual use of branching statement in a loop for (int i = 0; i < 10; i++) { if (i*i <= 25) { continue; } break; } // this makes more sense... for (int i = 0; i < 10; i++) { if (i*i > 25) { break; } } ]]> </example> </rule> <rule name="AvoidCallingFinalize" language="java" since="3.0" message="Avoid calling finalize() explicitly" class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidCallingFinalizeRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidcallingfinalize"> <description> The method Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. It should not be invoked by application logic. Note that Oracle has declared Object.finalize() as deprecated since JDK 9. </description> <priority>3</priority> <example> <![CDATA[ void foo() { Bar b = new Bar(); b.finalize(); } ]]> </example> </rule> <rule name="AvoidCatchingNPE" language="java" since="1.8" message="Avoid catching NullPointerException; consider removing the cause of the NPE." class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidcatchingnpe"> <description> Code should never throw NullPointerExceptions under normal circumstances. A catch block may hide the original error, causing other, more subtle problems later on. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //CatchStatement/FormalParameter/Type /ReferenceType/ClassOrInterfaceType[@Image='NullPointerException'] ]]> </value> </property> </properties> <example> <![CDATA[ public class Foo { void bar() { try { // do something } catch (NullPointerException npe) { } } } ]]> </example> </rule> <rule name="AvoidCatchingThrowable" language="java" since="1.2" message="A catch statement should never catch throwable since it includes errors." class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidCatchingThrowableRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidcatchingthrowable"> <description> Catching Throwable errors is not recommended since its scope is very broad. It includes runtime issues such as OutOfMemoryError that should be exposed and managed separately. </description> <priority>3</priority> <example> <![CDATA[ public void bar() { try { // do something } catch (Throwable th) { // should not catch Throwable th.printStackTrace(); } } ]]> </example> </rule> <rule name="AvoidDecimalLiteralsInBigDecimalConstructor" language="java" since="3.4" message="Avoid creating BigDecimal with a decimal (float/double) literal. Use a String literal" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoiddecimalliteralsinbigdecimalconstructor"> <description> One might assume that the result of "new BigDecimal(0.1)" is exactly equal to 0.1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding. The (String) constructor, on the other hand, is perfectly predictable: 'new BigDecimal("0.1")' is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //AllocationExpression[pmd-java:typeIs('java.math.BigDecimal')] [Arguments/ArgumentList/Expression/PrimaryExpression [ pmd-java:typeIs('float') or pmd-java:typeIs('java.lang.Float') or pmd-java:typeIs('double') or pmd-java:typeIs('java.lang.Double') ] ] ]]> </value> </property> </properties> <example> <![CDATA[ BigDecimal bd = new BigDecimal(1.123); // loss of precision, this would trigger the rule BigDecimal bd = new BigDecimal("1.123"); // preferred approach BigDecimal bd = new BigDecimal(12); // preferred approach, ok for integer values ]]> </example> </rule> <rule name="AvoidDuplicateLiterals" language="java" since="1.0" message="The String literal {0} appears {1} times in this file; the first occurrence is on line {2}" class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidDuplicateLiteralsRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidduplicateliterals"> <description> Code containing duplicate String literals can usually be improved by declaring the String as a constant field. </description> <priority>3</priority> <example> <![CDATA[ private void bar() { buz("Howdy"); buz("Howdy"); buz("Howdy"); buz("Howdy"); } private void buz(String x) {} ]]> </example> </rule> <rule name="AvoidEnumAsIdentifier" language="java" since="3.4" message="Avoid using enum as an identifier; it's a reserved word in JDK 1.5" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidenumasidentifier"> <description> Use of the term 'enum' will conflict with newer versions of Java since it is a reserved word. </description> <priority>2</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value>//VariableDeclaratorId[@Name='enum']</value> </property> </properties> <example> <![CDATA[ public class A { public class Foo { String enum = "foo"; } } ]]> </example> </rule> <rule name="AvoidFieldNameMatchingMethodName" language="java" since="3.0" message="Field {0} has the same name as a method" class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidFieldNameMatchingMethodNameRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidfieldnamematchingmethodname"> <description> It can be confusing to have a field name with the same name as a method. While this is permitted, having information (field) and actions (method) is not clear naming. Developers versed in Smalltalk often prefer this approach as the methods denote accessor methods. </description> <priority>3</priority> <example> <![CDATA[ public class Foo { Object bar; // bar is data or an action or both? void bar() { } } ]]> </example> </rule> <rule name="AvoidFieldNameMatchingTypeName" language="java" since="3.0" message="It is somewhat confusing to have a field name matching the declaring class name" class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidFieldNameMatchingTypeNameRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidfieldnamematchingtypename"> <description> It is somewhat confusing to have a field name matching the declaring class name. This probably means that type and/or field names should be chosen more carefully. </description> <priority>3</priority> <example> <![CDATA[ public class Foo extends Bar { int foo; // There is probably a better name that can be used } ]]> </example> </rule> <rule name="AvoidInstanceofChecksInCatchClause" language="java" since="3.0" message="An instanceof check is being performed on the caught exception. Create a separate catch clause for this exception type." class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidinstanceofchecksincatchclause"> <description> Each caught exception type should be handled in its own catch clause. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //CatchStatement/FormalParameter /following-sibling::Block//InstanceOfExpression/PrimaryExpression/PrimaryPrefix /Name[ @Image = ./ancestor::Block/preceding-sibling::FormalParameter /VariableDeclaratorId/@Name ] ]]> </value> </property> </properties> <example> <![CDATA[ try { // Avoid this // do something } catch (Exception ee) { if (ee instanceof IOException) { cleanup(); } } try { // Prefer this: // do something } catch (IOException ee) { cleanup(); } ]]> </example> </rule> <rule name="AvoidLosingExceptionInformation" since="4.2.6" language="java" message="Avoid statements in a catch block that invoke accessors on the exception without using the information" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidlosingexceptioninformation"> <description> Statements in a catch block that invoke accessors on the exception without using the information only add to code size. Either remove the invocation, or use the return result. </description> <priority>2</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //CatchStatement/Block/BlockStatement/Statement/StatementExpression/PrimaryExpression/PrimaryPrefix/Name [ @Image = concat(../../../../../../../FormalParameter/VariableDeclaratorId/@Name, '.getMessage') or @Image = concat(../../../../../../../FormalParameter/VariableDeclaratorId/@Name, '.getLocalizedMessage') or @Image = concat(../../../../../../../FormalParameter/VariableDeclaratorId/@Name, '.getCause') or @Image = concat(../../../../../../../FormalParameter/VariableDeclaratorId/@Name, '.getStackTrace') or @Image = concat(../../../../../../../FormalParameter/VariableDeclaratorId/@Name, '.toString') ] ]]> </value> </property> </properties> <example> <![CDATA[ public void bar() { try { // do something } catch (SomeException se) { se.getMessage(); } } ]]> </example> </rule> <rule name="AvoidMultipleUnaryOperators" language="java" since="4.2" class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidMultipleUnaryOperatorsRule" message="Using multiple unary operators may be a bug, and/or is confusing." externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidmultipleunaryoperators"> <description> The use of multiple unary operators may be problematic, and/or confusing. Ensure that the intended usage is not a bug, or consider simplifying the expression. </description> <priority>2</priority> <example> <![CDATA[ // These are typo bugs, or at best needlessly complex and confusing: int i = - -1; int j = + - +1; int z = ~~2; boolean b = !!true; boolean c = !!!true; // These are better: int i = 1; int j = -1; int z = 2; boolean b = true; boolean c = false; // And these just make your brain hurt: int i = ~-2; int j = -~7; ]]> </example> </rule> <rule name="AvoidUsingOctalValues" language="java" since="3.9" message="Do not start a literal by 0 unless it's an octal value" class="net.sourceforge.pmd.lang.java.rule.errorprone.AvoidUsingOctalValuesRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidusingoctalvalues"> <description> Integer literals should not start with zero since this denotes that the rest of literal will be interpreted as an octal value. </description> <priority>3</priority> <example> <![CDATA[ int i = 012; // set i with 10 not 12 int j = 010; // set j with 8 not 10 k = i * j; // set k with 80 not 120 ]]> </example> </rule> <rule name="BadComparison" language="java" since="1.8" message="Avoid equality comparisons with Double.NaN" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#badcomparison"> <description> Avoid equality comparisons with Double.NaN. Due to the implicit lack of representation precision when comparing floating point numbers these are likely to cause logic errors. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //EqualityExpression[@Image='=='] /PrimaryExpression/PrimaryPrefix /Name[@Image='Double.NaN' or @Image='Float.NaN'] ]]> </value> </property> </properties> <example> <![CDATA[ boolean x = (y == Double.NaN); ]]> </example> </rule> <rule name="BrokenNullCheck" language="java" since="3.8" message="Method call on object which may be null" class="net.sourceforge.pmd.lang.java.rule.errorprone.BrokenNullCheckRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#brokennullcheck"> <description> The null check is broken since it will throw a NullPointerException itself. It is likely that you used || instead of &amp;&amp; or vice versa. </description> <priority>2</priority> <example> <![CDATA[ public String bar(String string) { // should be && if (string!=null || !string.equals("")) return string; // should be || if (string==null && string.equals("")) return string; } ]]> </example> </rule> <rule name="CallSuperFirst" since="4.2.5" language="java" message="super should be called at the start of the method" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#callsuperfirst"> <description>Super should be called at the start of the method</description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //MethodDeclaration[ @Name='onCreate' or @Name='onConfigurationChanged' or @Name='onPostCreate' or @Name='onPostResume' or @Name='onRestart' or @Name='onRestoreInstanceState' or @Name='onResume' or @Name='onStart' ] /Block[not( (BlockStatement[1]/Statement/StatementExpression/PrimaryExpression[./PrimaryPrefix[@SuperModifier= true()]]/PrimarySuffix[@Image= ancestor::MethodDeclaration/@Name]))] [ancestor::ClassOrInterfaceDeclaration[ExtendsList/ClassOrInterfaceType[ pmd-java:typeIs('android.app.Activity') or pmd-java:typeIs('android.app.Application') or pmd-java:typeIs('android.app.Service') ]]] ]]> </value> </property> </properties> <example> <![CDATA[ public class DummyActivity extends Activity { public void onCreate(Bundle bundle) { // missing call to super.onCreate(bundle) foo(); } } ]]> </example> </rule> <rule name="CallSuperLast" since="4.2.5" language="java" message="super should be called at the end of the method" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#callsuperlast"> <description> Super should be called at the end of the method </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //MethodDeclaration[ @Name='finish' or @Name='onDestroy' or @Name='onPause' or @Name='onSaveInstanceState' or @Name='onStop' or @Name='onTerminate' ] /Block/BlockStatement[last()] [not(Statement/StatementExpression/PrimaryExpression[./PrimaryPrefix[@SuperModifier= true()]]/PrimarySuffix[@Image= ancestor::MethodDeclaration/@Name])] [ancestor::ClassOrInterfaceDeclaration[ExtendsList/ClassOrInterfaceType[ pmd-java:typeIs('android.app.Activity') or pmd-java:typeIs('android.app.Application') or pmd-java:typeIs('android.app.Service') ]]] ]]> </value> </property> </properties> <example> <![CDATA[ public class DummyActivity extends Activity { public void onPause() { foo(); // missing call to super.onPause() } } ]]> </example> </rule> <rule name="CheckSkipResult" language="java" since="5.0" message="Check the value returned by the skip() method of an InputStream to see if the requested number of bytes has been skipped." class="net.sourceforge.pmd.lang.java.rule.errorprone.CheckSkipResultRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#checkskipresult"> <description> The skip() method may skip a smaller number of bytes than requested. Check the returned value to find out if it was the case or not. </description> <priority>3</priority> <example> <![CDATA[ public class Foo { private FileInputStream _s = new FileInputStream("file"); public void skip(int n) throws IOException { _s.skip(n); // You are not sure that exactly n bytes are skipped } public void skipExactly(int n) throws IOException { while (n != 0) { long skipped = _s.skip(n); if (skipped == 0) throw new EOFException(); n -= skipped; } } ]]> </example> </rule> <rule name="ClassCastExceptionWithToArray" language="java" since="3.4" message="This usage of the Collection.toArray() method will throw a ClassCastException." class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#classcastexceptionwithtoarray"> <description> When deriving an array of a specific class from your Collection, one should provide an array of the same class as the parameter of the toArray() method. Doing otherwise you will will result in a ClassCastException. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //CastExpression[Type/ReferenceType/ClassOrInterfaceType[@Image != "Object"]] /PrimaryExpression [PrimaryPrefix/Name[ends-with(@Image, '.toArray')]] [PrimarySuffix/Arguments[not(*)]] [count(PrimarySuffix) = 1] ]]> </value> </property> </properties> <example> <![CDATA[ Collection c = new ArrayList(); Integer obj = new Integer(1); c.add(obj); // this would trigger the rule (and throw a ClassCastException if executed) Integer[] a = (Integer [])c.toArray(); // this is fine and will not trigger the rule Integer[] b = (Integer [])c.toArray(new Integer[c.size()]); ]]> </example> </rule> <rule name="CloneMethodMustBePublic" language="java" since="5.4.0" message="clone() method must be public if the class implements Cloneable" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#clonemethodmustbepublic"> <description> The java Manual says "By convention, classes that implement this interface should override Object.clone (which is protected) with a public method." </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //MethodDeclaration[@Public= false()] [@Name = 'clone'] [@Arity = 0] ]]> </value> </property> </properties> <example> <![CDATA[ public class Foo implements Cloneable { @Override protected Object clone() throws CloneNotSupportedException { // Violation, must be public } } public class Foo implements Cloneable { @Override protected Foo clone() { // Violation, must be public } } public class Foo implements Cloneable { @Override public Object clone() // Ok } ]]> </example> </rule> <rule name="CloneMethodMustImplementCloneable" language="java" since="1.9" message="clone() method should be implemented only if implementing Cloneable interface" class="net.sourceforge.pmd.lang.java.rule.errorprone.CloneMethodMustImplementCloneableRule" typeResolution="true" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#clonemethodmustimplementcloneable"> <description> The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException. The rule can also detect, if the class implements or extends a Cloneable class. </description> <priority>3</priority> <example> <![CDATA[ public class MyClass { public Object clone() throws CloneNotSupportedException { return foo; } } ]]> </example> </rule> <rule name="CloneMethodReturnTypeMustMatchClassName" language="java" minimumLanguageVersion="1.5" since="5.4.0" message="The return type of the clone() method must be the class name when implements Cloneable" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#clonemethodreturntypemustmatchclassname"> <description> If a class implements cloneable the return type of the method clone() must be the class name. That way, the caller of the clone method doesn't need to cast the returned clone to the correct type. Note: This is only possible with Java 1.5 or higher. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //MethodDeclaration [ @Name = 'clone' and @Arity = 0 and not (ResultType//ClassOrInterfaceType/@Image = ancestor::ClassOrInterfaceDeclaration[1]/@SimpleName) ] ]]> </value> </property> </properties> <example> <![CDATA[ public class Foo implements Cloneable { @Override protected Object clone() { // Violation, Object must be Foo } } public class Foo implements Cloneable { @Override public Foo clone() { //Ok } } ]]> </example> </rule> <rule name="CloneThrowsCloneNotSupportedException" language="java" since="1.9" message="clone() method should throw CloneNotSupportedException" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#clonethrowsclonenotsupportedexception"> <description> The method clone() should throw a CloneNotSupportedException. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //MethodDeclaration [ @Name = 'clone' and @Arity = 0 and count(NameList/Name[contains (@Image,'CloneNotSupportedException')]) = 0 ] [ ../../../../ClassOrInterfaceDeclaration[@Final = false()] ] ]]> </value> </property> </properties> <example> <![CDATA[ public class MyClass implements Cloneable{ public Object clone() { // will cause an error MyClass clone = (MyClass)super.clone(); return clone; } } ]]> </example> </rule> <rule name="CloseResource" language="java" since="1.2.2" message="Ensure that resources like this {0} object are closed after use" class="net.sourceforge.pmd.lang.java.rule.errorprone.CloseResourceRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#closeresource"> <description> Ensure that resources (like `java.sql.Connection`, `java.sql.Statement`, and `java.sql.ResultSet` objects and any subtype of `java.lang.AutoCloseable`) are always closed after use. Failing to do so might result in resource leaks. Note: It suffices to configure the super type, e.g. `java.lang.AutoClosable`, so that this rule automatically triggers on any subtype (e.g. `java.io.FileInputStream`). Additionally specifying `java.sql.Connection` helps in detecting the types, if the type resolution / auxclasspath is not correctly setup. Note: Since PMD 6.16.0 the default value for the property `types` contains `java.lang.AutoCloseable` and detects now cases where the standard `java.io.*Stream` classes are involved. In order to restore the old behaviour, just remove "AutoCloseable" from the types. </description> <priority>3</priority> <example> <![CDATA[ public class Bar { public void withSQL() { Connection c = pool.getConnection(); try { // do stuff } catch (SQLException ex) { // handle exception } finally { // oops, should close the connection using 'close'! // c.close(); } } public void withFile() { InputStream file = new FileInputStream(new File("/tmp/foo")); try { int c = file.in(); } catch (IOException e) { // handle exception } finally { // TODO: close file } } } ]]> </example> </rule> <rule name="CompareObjectsWithEquals" language="java" since="3.2" message="Use equals() to compare object references." class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#compareobjectswithequals"> <description> Use equals() to compare object references; avoid comparing them with ==. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //EqualityExpression [count(PrimaryExpression [pmd-java:typeIs('java.lang.Object')] [not(pmd-java:typeIs('java.lang.Enum'))] [not(pmd-java:typeIs('java.lang.Class'))]) = 2 ] [not(PrimaryExpression[PrimaryPrefix/@ThisModifier = true()] [not(PrimarySuffix)] [ancestor::MethodDeclaration[@Name = 'equals']]) ] ]]> </value> </property> </properties> <example> <![CDATA[ class Foo { boolean bar(String a, String b) { return a == b; } } ]]> </example> </rule> <!-- <rule name="ConstructorCallsOverridableMethod"--> <!-- language="java"--> <!-- since="1.04"--> <!-- message="Overridable {0} called during object construction"--> <!-- class="net.sourceforge.pmd.lang.java.rule.errorprone.ConstructorCallsOverridableMethodRule"--> <!-- externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#constructorcallsoverridablemethod">--> <!-- <description>--> <!-- Calling overridable methods during construction poses a risk of invoking methods on an incompletely--> <!-- constructed object and can be difficult to debug.--> <!-- It may leave the sub-class unable to construct its superclass or forced to replicate the construction--> <!-- process completely within itself, losing the ability to call super(). If the default constructor--> <!-- contains a call to an overridable method, the subclass may be completely uninstantiable. Note that--> <!-- this includes method calls throughout the control flow graph - i.e., if a constructor Foo() calls a--> <!-- private method bar() that calls a public method buz(), this denotes a problem.--> <!-- </description>--> <!-- <priority>1</priority>--> <!-- <example>--> <!-- <![CDATA[--> <!--public class SeniorClass {--> <!-- public SeniorClass(){--> <!-- toString(); //may throw NullPointerException if overridden--> <!-- }--> <!-- public String toString(){--> <!-- return "IAmSeniorClass";--> <!-- }--> <!--}--> <!--public class JuniorClass extends SeniorClass {--> <!-- private String name;--> <!-- public JuniorClass(){--> <!-- super(); //Automatic call leads to NullPointerException--> <!-- name = "JuniorClass";--> <!-- }--> <!-- public String toString(){--> <!-- return name.toUpperCase();--> <!-- }--> <!--}--> <!--]]>--> <!-- </example>--> <!-- </rule>--> <rule name="DetachedTestCase" language="java" since="6.13.0" message="Probable detached JUnit test case." class="net.sourceforge.pmd.lang.rule.XPathRule" typeResolution="true" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#detachedtestcase"> <description> The method appears to be a test case since it has public or default visibility, non-static access, no arguments, no return value, has no annotations, but is a member of a class that has one or more JUnit test cases. If it is a utility method, it should likely have private visibility. If it is an ignored test, it should be annotated with @Test and @Ignore. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value><![CDATA[ //ClassOrInterfaceBodyDeclaration [../ClassOrInterfaceBodyDeclaration/Annotation/*/Name [pmd-java:typeIs('org.junit.Test') or pmd-java:typeIs('org.junit.jupiter.api.Test') or pmd-java:typeIs('org.junit.jupiter.api.RepeatedTest') or pmd-java:typeIs('org.junit.jupiter.api.TestFactory') or pmd-java:typeIs('org.junit.jupiter.api.TestTemplate') or pmd-java:typeIs('org.junit.jupiter.params.ParameterizedTest')] ] [not(Annotation)] [MethodDeclaration[(@Public = true() or @PackagePrivate = true()) and @Static = false() and ResultType[@Void = true()] and MethodDeclarator/FormalParameters[@Size = 0] ] ] ]]></value> </property> <property name="version" value="2.0" /> </properties> <example> <![CDATA[ public class MyTest { @Test public void someTest() { } // violation: Not annotated public void someOtherTest () { } } ]]> </example> </rule> <rule name="DoNotCallGarbageCollectionExplicitly" language="java" since="4.2" message="Do not explicitly trigger a garbage collection." class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#donotcallgarbagecollectionexplicitly"> <description> Calls to System.gc(), Runtime.getRuntime().gc(), and System.runFinalization() are not advised. Code should have the same behavior whether the garbage collection is disabled using the option -Xdisableexplicitgc or not. Moreover, "modern" jvms do a very good job handling garbage collections. If memory usage issues unrelated to memory leaks develop within an application, it should be dealt with JVM options rather than within the code itself. </description> <priority>2</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //Name[ (starts-with(@Image, 'System.') and (starts-with(@Image, 'System.gc') or starts-with(@Image, 'System.runFinalization'))) or ( starts-with(@Image,'Runtime.getRuntime') and ../../PrimarySuffix[ends-with(@Image,'gc')] ) ] ]]> </value> </property> </properties> <example> <![CDATA[ public class GCCall { public GCCall() { // Explicit gc call ! System.gc(); } public void doSomething() { // Explicit gc call ! Runtime.getRuntime().gc(); } public explicitGCcall() { // Explicit gc call ! System.gc(); } public void doSomething() { // Explicit gc call ! Runtime.getRuntime().gc(); } } ]]> </example> </rule> <rule name="DoNotExtendJavaLangThrowable" language="java" since="6.0.0" message="Exceptions should not extend java.lang.Throwable" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#donotextendjavalangthrowable"> <description> Extend Exception or RuntimeException instead of Throwable. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //ClassOrInterfaceDeclaration/ExtendsList/ClassOrInterfaceType [@Image="Throwable" or @Image="java.lang.Throwable"] ]]> </value> </property> </properties> <example> <![CDATA[ public class Foo extends Throwable { } ]]> </example> </rule> <rule name="DoNotHardCodeSDCard" since="4.2.6" language="java" message="Do not hardcode /sdcard." class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#donothardcodesdcard"> <description> Use Environment.getExternalStorageDirectory() instead of "/sdcard" </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value>//Literal[starts-with(@Image,'"/sdcard')]</value> </property> </properties> <example> <![CDATA[ public class MyActivity extends Activity { protected void foo() { String storageLocation = "/sdcard/mypackage"; // hard-coded, poor approach storageLocation = Environment.getExternalStorageDirectory() + "/mypackage"; // preferred approach } } ]]> </example> </rule> <rule name="DoNotTerminateVM" language="java" since="4.1" message="System.exit() should not be used in J2EE/JEE apps" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#donotterminatevm"> <description> Web applications should not call `System.exit()`, since only the web container or the application server should stop the JVM. Otherwise a web application would terminate all other applications running on the same application server. This rule also checks for the equivalent calls `Runtime.getRuntime().exit()` and `Runtime.getRuntime().halt()`. This rule was called *DoNotCallSystemExit* until PMD 6.29.0. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //Name[ starts-with(@Image,'System.exit') or (starts-with(@Image,'Runtime.getRuntime') and ../../PrimarySuffix[ends-with(@Image,'exit') or ends-with(@Image,'halt')]) ][not(ancestor::MethodDeclaration[1][@Name="main" and @Static = true()])] ]]> </value> </property> </properties> <example> <![CDATA[ public void bar() { System.exit(0); // never call this when running in an application server! } public void foo() { Runtime.getRuntime().exit(0); // never stop the JVM manually, the container will do this. } ]]> </example> </rule> <rule name="DoNotThrowExceptionInFinally" language="java" since="4.2" message="A throw statement in a finally block makes the control flow hard to understand." class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#donotthrowexceptioninfinally"> <description> Throwing exceptions within a 'finally' block is confusing since they may mask other exceptions or code defects. Note: This is a PMD implementation of the Lint4j rule "A throw in a finally block" </description> <priority>4</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value>//FinallyStatement[descendant::ThrowStatement]</value> </property> </properties> <example> <![CDATA[ public class Foo { public void bar() { try { // Here do some stuff } catch( Exception e) { // Handling the issue } finally { // is this really a good idea ? throw new Exception(); } } } ]]> </example> </rule> <rule name="DontImportSun" language="java" since="1.5" message="Avoid importing anything from the 'sun.*' packages" class="net.sourceforge.pmd.lang.java.rule.errorprone.DontImportSunRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#dontimportsun"> <description> Avoid importing anything from the 'sun.*' packages. These packages are not portable and are likely to change. </description> <priority>4</priority> <example> <![CDATA[ import sun.misc.foo; public class Foo {} ]]> </example> </rule> <rule name="DontUseFloatTypeForLoopIndices" language="java" since="4.3" message="Don't use floating point for loop indices. If you must use floating point, use double." class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#dontusefloattypeforloopindices"> <description> Don't use floating point for loop indices. If you must use floating point, use double unless you're certain that float provides enough precision and you have a compelling performance need (space or time). </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //ForStatement/ForInit/LocalVariableDeclaration /Type/PrimitiveType[@Image="float"] ]]> </value> </property> </properties> <example> <![CDATA[ public class Count { public static void main(String[] args) { final int START = 2000000000; int count = 0; for (float f = START; f < START + 50; f++) count++; //Prints 0 because (float) START == (float) (START + 50). System.out.println(count); //The termination test misbehaves due to floating point granularity. } } ]]> </example> </rule> <rule name="EmptyCatchBlock" language="java" since="0.1" message="Avoid empty catch blocks" class="net.sourceforge.pmd.lang.rule.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#emptycatchblock"> <description> Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this swallows an exception which should either be acted on or reported. </description> <priority>3</priority> <properties> <property name="version" value="2.0"/> <property name="xpath"> <value> <![CDATA[ //CatchStatement [not(Block/BlockStatement)] [$allowCommentedBlocks != true() or Block/@containsComment = false()] [FormalParameter/Type/ReferenceType /ClassOrInterfaceType[@Image != 'InterruptedException' and @Image != 'CloneNotSupportedException'] ] [FormalParameter/VariableDeclaratorId[not(matches(@Name, $allowExceptionNameRegex))]] ]]> </value> </property> <property name="allowCommentedBlocks" type="Boolean" description="Empty blocks containing comments will be skipped" value="false"/> <property name="allowExceptionNameRegex" type="String" description="Empty blocks catching exceptions with names matching this regular expression will be skipped" value="^(ignored|expected)$"/> </properties> <example> <![CDATA[ public void doSomething() { try { F