All Downloads are FREE. Search and download functionalities are using the official Maven repository.

rulesets.java.controversial.xml Maven / Gradle / Ivy

There is a newer version: 2.0.9
Show newest version
<?xml version="1.0"?>

<ruleset name="Controversial"
    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 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">

  <description>
The Controversial ruleset contains rules that, for whatever reason, are considered controversial.
They are held here to allow people to include them as they see fit within their custom rulesets.
  </description>

    <rule name="UnnecessaryConstructor"
       language="java"
         since="1.0"
          message="Avoid unnecessary constructors - the compiler will generate these for you"
          class="net.sourceforge.pmd.lang.rule.XPathRule"
          externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#UnnecessaryConstructor">
      <description>
This rule detects when a constructor is not necessary; i.e., when there is only one constructor,
its public, has an empty body, and takes no arguments.
      </description>
      <priority>3</priority>
        <properties>
            <property name="xpath">
                <value>
                    <![CDATA[
//ClassOrInterfaceBody[count(ClassOrInterfaceBodyDeclaration/ConstructorDeclaration)=1]
/ClassOrInterfaceBodyDeclaration/ConstructorDeclaration
[@Public='true']
[not(FormalParameters/*)]
[not(BlockStatement)]
[not(NameList)]
[count(ExplicitConstructorInvocation/Arguments/ArgumentList/Expression)=0]
                    ]]>
                </value>
            </property>
        </properties>
      <example>
  <![CDATA[
public class Foo {
  public Foo() {}
}
  ]]>
      </example>
    </rule>

    <rule name="NullAssignment"
         since="1.02"
          message="Assigning an Object to null is a code smell.  Consider refactoring."
          class="net.sourceforge.pmd.lang.java.rule.controversial.NullAssignmentRule"
          externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#NullAssignment">
      <description>
Assigning a "null" to a variable (outside of its declaration) is usually bad form.  Sometimes, this type
of assignment is an indication that the programmer doesn't completely understand what is going on in the code.

NOTE: This sort of assignment may used in some cases to dereference objects and encourage garbage collection.
      </description>
        <priority>3</priority>
      <example>
 <![CDATA[
public void bar() {
  Object x = null; // this is OK
  x = new Object();
     // big, complex piece of code here
  x = null; // this is not required
     // big, complex piece of code here
}

 ]]>
      </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.controversial.OnlyOneReturnRule"
          externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.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="AssignmentInOperand"
      since="1.03"
      message="Avoid assignments in operands"
      class="net.sourceforge.pmd.lang.java.rule.controversial.AssignmentInOperandRule"
          externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.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="AtLeastOneConstructor"
       language="java"
      since="1.04"
      message="Each class should declare at least one constructor"
      class="net.sourceforge.pmd.lang.rule.XPathRule"
          externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#AtLeastOneConstructor">
  <description>
Each class should declare at least one constructor.
  </description>
  <priority>3</priority>
  <properties>
      <property name="xpath">
          <value>
              <![CDATA[
//ClassOrInterfaceDeclaration[
  not(ClassOrInterfaceBody/ClassOrInterfaceBodyDeclaration/ConstructorDeclaration)
  and
  (@Static = 'false')
  and
  (count(./descendant::MethodDeclaration[@Static = 'true']) < 1)
]
  [@Interface='false']
]]>
          </value>
      </property>
  </properties>
  <example>
  <![CDATA[
public class Foo {
   // missing constructor
  public void doSomething() { ... }
  public void doOtherThing { ... }
}
  ]]>
  </example>
</rule>

    <rule name="DontImportSun"
       since="1.5"
       message="Avoid importing anything from the 'sun.*' packages"
       class="net.sourceforge.pmd.lang.java.rule.controversial.DontImportSunRule"
          externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.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="SuspiciousOctalEscape"
       since="1.5"
       message="Suspicious decimal characters following octal escape in string literal"
          class="net.sourceforge.pmd.lang.java.rule.controversial.SuspiciousOctalEscapeRule"
          externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#SuspiciousOctalEscape">
      <description>
A suspicious octal escape sequence was found inside a String literal.
The Java language specification (section 3.10.6) says an octal
escape sequence inside a literal String shall consist of a backslash
followed by:

   OctalDigit | OctalDigit OctalDigit | ZeroToThree OctalDigit OctalDigit

Any octal escape sequence followed by non-octal digits can be confusing,
e.g. "\038" is interpreted as the octal escape sequence "\03" followed by
the literal character "8".
      </description>
      <priority>3</priority>
      <example>
<![CDATA[
public void foo() {
  // interpreted as octal 12, followed by character '8'
  System.out.println("suspicious: \128");
}
]]>
      </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="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.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="UnnecessaryParentheses"
       language="java"
         since="3.1"
          message="This statement may have some unnecessary parentheses"
          class="net.sourceforge.pmd.lang.rule.XPathRule"
          externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#UnnecessaryParentheses">
      <description>
Sometimes expressions are wrapped in unnecessary parentheses, making them look like function calls.
      </description>
      <priority>3</priority>
      <properties>
          <property name="xpath">
              <value>
                  <![CDATA[
          //Expression
           /PrimaryExpression
            /PrimaryPrefix
             /Expression[count(*)=1]
              /PrimaryExpression
              /PrimaryPrefix]]>
              </value>
          </property>
      </properties>
      <example>
  <![CDATA[
public class Foo {
   boolean bar() {
      return (true);
      }
}
  ]]>
      </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="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.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="DataflowAnomalyAnalysis"
          since="3.9"
              message="Found ''{0}''-anomaly for variable ''{1}'' (lines ''{2}''-''{3}'')."
              class="net.sourceforge.pmd.lang.java.rule.controversial.DataflowAnomalyAnalysisRule"
              dfa="true"
              externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#DataflowAnomalyAnalysis">
          <description>The dataflow analysis tracks local definitions, undefinitions and references to variables on different paths on the data flow.
From those informations there can be found various problems.

1. UR - Anomaly: There is a reference to a variable that was not defined before. This is a bug and leads to an error.
2. DU - Anomaly: A recently defined variable is undefined. These anomalies may appear in normal source text.
3. DD - Anomaly: A recently defined variable is redefined. This is ominous but don't have to be a bug.
          </description>
          <priority>5</priority>
          <example>
<![CDATA[
public void foo() {
  int buz = 5;
  buz = 6; // redefinition of buz -> dd-anomaly
  foo(buz);
  buz = 2;
} // buz is undefined when leaving scope -> du-anomaly
]]>
          </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="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#AvoidFinalLocalVariable">
          <description><![CDATA[
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="AvoidUsingShortType"
       language="java"
        since="4.1"
        message="Do not use the short type"
        class="net.sourceforge.pmd.lang.rule.XPathRule"
      externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#AvoidUsingShortType">
        <description>
            <![CDATA[
Java uses the 'short' type to reduce memory usage, not to optimize calculation. In fact, the JVM does not have any
arithmetic capabilities for the short type: the JVM must convert the short into an int, do the proper calculation
and convert the int back to a short. Thus any storage gains found through use of the 'short' type may be offset by
adverse impacts on performance.
            ]]>
        </description>
        <priority>1</priority>
        <properties>
            <property name="xpath">
                <value>
                    <![CDATA[
            //PrimitiveType[@Image = 'short']
                    ]]>
                </value>
            </property>
        </properties>
        <example>
            <![CDATA[
public class UsingShort {
   private short doNotUseShort = 0;

   public UsingShort() {
    short shouldNotBeUsed = 1;
    doNotUseShort += shouldNotBeUsed;
  }
}
       ]]>
     </example>
   </rule>

  <rule
        name="AvoidUsingVolatile"
       language="java"
        since="4.1"
        class="net.sourceforge.pmd.lang.rule.XPathRule"
        message="Use of modifier volatile is not recommended."
      externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#AvoidUsingVolatile">

        <description>
            <![CDATA[
Use of the keyword 'volatile' is generally used to fine tune a Java application, and therefore, requires
a good expertise of the Java Memory Model. Moreover, its range of action is somewhat misknown. Therefore,
the volatile keyword should not be used for maintenance purpose and portability.
            ]]>
        </description>
        <priority>2</priority>
        <properties>
            <property name="xpath">
                <value>
                    <![CDATA[
                        //FieldDeclaration[
                                contains(@Volatile,'true')
                        ]
                    ]]>
                </value>
            </property>
        </properties>
    <example>
      <![CDATA[
public class ThrDeux {
  private volatile String var1;	// not suggested
  private          String var2;	// preferred
}
      ]]>
    </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="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#AvoidUsingNativeCode">
        <description>
            <![CDATA[
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>
                    <![CDATA[
                        //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="AvoidAccessibilityAlteration"
       language="java"
      since="4.1"
        message="You should modify visibility of class or methods using getDeclaredConstructors(), getDeclaredConstructor(Class[]), setAccessible() or PrivilegedAction."
        class="net.sourceforge.pmd.lang.rule.XPathRule"
        externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#AvoidAccessibilityAlteration">
        <description>
            <![CDATA[
Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(),
as the interface PrivilegedAction, allows 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="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="DoNotCallGarbageCollectionExplicitly"
       language="java"
          since="4.2"
            message="Do not explicitly trigger a garbage collection."
            class="net.sourceforge.pmd.lang.rule.XPathRule"
            externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#DoNotCallGarbageCollectionExplicitly">
        <description>
          <![CDATA[
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="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="OneDeclarationPerLine"
       language="java"
        since="5.0"
        class="net.sourceforge.pmd.lang.rule.XPathRule"
        message="Use one line for each declaration, it enhances code readability."
        externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#OneDeclarationPerLine">
        <description>
            <![CDATA[
Java allows the use of several variables declaration of the same type on one line. However, it
can lead to quite messy code. This rule looks for several declarations on the same line.
            ]]>
        </description>
       <priority>4</priority>
       <properties>
            <property name="xpath">
                <value>
                    <![CDATA[
//LocalVariableDeclaration
   [count(VariableDeclarator) > 1]
   [$strictMode or count(distinct-values(VariableDeclarator/@BeginLine)) != count(VariableDeclarator)]
                    ]]>
                </value>
            </property>
            <property name="version" value="2.0"/>
            <property name="strictMode" type="Boolean" value="false"
                      description="If true, mark combined declaration even if the declarations are on separate lines."/>
        </properties>
        <example>
          <![CDATA[
String name;            // separate declarations
String lastname;

String name, lastname;  // combined declaration, a violation

String name,
       lastname;        // combined declaration on multiple lines, no violation by default.
                        // Set property strictMode to true to mark this as violation.
          ]]>
        </example>
  </rule>

  <rule
        name="AvoidPrefixingMethodParameters"
       language="java"
        since="5.0"
        class="net.sourceforge.pmd.lang.rule.XPathRule"
        message="Avoid prefixing parameters by in, out or inOut. Uses Javadoc to document this behavior."
        externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#AvoidPrefixingMethodParameters">
        <description>
            <![CDATA[
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.
            ]]>
        </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="AvoidLiteralsInIfCondition"
      language="java" since="4.2.6"
      message="Avoid using Literals in Conditional Statements"
      class="net.sourceforge.pmd.lang.rule.XPathRule"
      externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#AvoidLiteralsInIfCondition">
    <description>
Avoid using hard-coded literals in conditional statements. By declaring them as static variables
or private members with descriptive names maintainability is enhanced. By default, the literals "-1" and "0" are ignored.
More exceptions can be defined with the property "ignoreMagicNumbers".
    </description>
    <priority>3</priority>
    <properties>
      <property name="ignoreMagicNumbers" description="Comma-separated list of magic numbers, that should be ignored"
        type="String" value="-1,0"/>
      <property name="xpath">
        <value>
<![CDATA[
//IfStatement/Expression/*/PrimaryExpression/PrimaryPrefix/Literal
[not(NullLiteral)]
[not(BooleanLiteral)]
[empty(index-of(tokenize($ignoreMagicNumbers, ','), @Image))]
]]>
        </value>
      </property>
      <property name="version" value="2.0"/>
    </properties>
    <example>
<![CDATA[
private static final int MAX_NUMBER_OF_REQUESTS = 10;

public void checkRequests() {

    if (i == 10) {                        // magic number, buried in a method
      doSomething();
    }

    if (i == MAX_NUMBER_OF_REQUESTS) {    // preferred approach
      doSomething();
    }

    if (aString.indexOf('.') != -1) {}     // magic number -1, by default ignored
    if (aString.indexOf('.') >= 0) { }     // alternative approach

    if (aDouble > 0.0) {}                  // magic number 0.0
    if (aDouble >= Double.MIN_VALUE) {}    // preferred approach
}
]]>
    </example>
  </rule>

  <rule  name="UseObjectForClearerAPI"
         language="java" since="4.2.6"
         message="Rather than using a lot of String arguments, consider using a container object for those values."
         class="net.sourceforge.pmd.lang.rule.XPathRule"
         externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#UseObjectForClearerAPI">
    <description>
When you write a public method, you should be thinking in terms of an API. If your method is public, it means other class
will use it, therefore, you want (or need) to offer a comprehensive and evolutive API. If you pass a lot of information
as a simple series of Strings, you may think of using an Object to represent all those information. You'll get a simplier
API (such as doWork(Workload workload), rather than a tedious series of Strings) and more importantly, if you need at some
point to pass extra data, you'll be able to do so by simply modifying or extending Workload without any modification to
your API.
    </description>
    <priority>3</priority>
    <properties>
      <property name="xpath">
        <value>
<![CDATA[
//MethodDeclaration[@Public]/MethodDeclarator/FormalParameters[
     count(FormalParameter/Type/ReferenceType/ClassOrInterfaceType[@Image = 'String']) > 3
]
]]>
        </value>
      </property>
    </properties>
    <example>
<![CDATA[
public class MyClass {
  public void connect(String username,
    String pssd,
    String databaseName,
    String databaseAdress)
    // Instead of those parameters object
    // would ensure a cleaner API and permit
    // to add extra data transparently (no code change):
    // void connect(UserData data);
    {

  }
}
]]>
    </example>
  </rule>


  <rule  name="UseConcurrentHashMap"
         language="java"
         since="4.2.6"
         message="If you run in Java5 or newer and have concurrent access, you should use the ConcurrentHashMap implementation"
         class="net.sourceforge.pmd.lang.rule.XPathRule"
         externalInfoUrl="https://pmd.github.io/pmd-5.4.1/pmd-java/rules/java/controversial.html#UseConcurrentHashMap">
    <description>
Since Java5 brought a new implementation of the Map designed for multi-threaded access, you can
perform efficient map reads without blocking other threads.
    </description>
    <priority>3</priority>
    <properties>
      <property name="xpath">
        <value>
<![CDATA[
//Type[../VariableDeclarator/VariableInitializer//AllocationExpression/ClassOrInterfaceType[@Image != 'ConcurrentHashMap']]
/ReferenceType/ClassOrInterfaceType[@Image = 'Map']
]]>
        </value>
      </property>
    </properties>
    <example>
<![CDATA[
public class ConcurrentApp {
  public void getMyInstance() {
    Map map1 = new HashMap(); 	// fine for single-threaded access
    Map map2 = new ConcurrentHashMap();  // preferred for use with multiple threads

    // the following case will be ignored by this rule
    Map map3 = someModule.methodThatReturnMap(); // might be OK, if the returned map is already thread-safe
  }
}
]]>
    </example>
  </rule>

</ruleset>




© 2015 - 2025 Weber Informatics LLC | Privacy Policy