<?xml version="1.0"?>

<ruleset name="Controversial Rules"
    xmlns="http://pmd.sf.net/ruleset/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
    xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">

  <description>
The Controversial Ruleset contains rules that, for whatever reason, are considered controversial.  They
are separated out here to allow people to include as they see fit via custom rulesets.  This ruleset was
initially created in response to discussions over UnnecessaryConstructorRule which Tom likes but
most people really dislike :-)
  </description>

    <rule name="UnnecessaryConstructor"
    		 since="1.0"
          message="Avoid unnecessary constructors - the compiler will generate these for you"
          class="net.sourceforge.pmd.rules.XPathRule"
          externalInfoUrl="http://pmd.sourceforge.net/rules/controversial.html#UnnecessaryConstructor">
      <description>
This rule detects when a constructor is not necessary; i.e., when there's only one constructor,
it's 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.rules.design.NullAssignmentRule"
          externalInfoUrl="http://pmd.sourceforge.net/rules/controversial.html#NullAssignment">
      <description>
 Assigning a "null" to a variable (outside of its declaration) is usually
 bad form.  Some times, the assignment is an indication that the programmer doesn't
 completely understand what is going on in the code.  NOTE: This sort of assignment
 may in rare cases be useful to encourage garbage collection.  If that's what you're using
 it for, by all means, disregard this rule :-)
      </description>
        <priority>3</priority>
      <example>
 <![CDATA[
 public class Foo {
   public void bar() {
     Object x = null; // This is OK.
     x = new Object();
     // Big, complex piece of code here.
     x = null; // This is BAD.
     // 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.rules.design.OnlyOneReturnRule"
          externalInfoUrl="http://pmd.sourceforge.net/rules/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";   // oops, multiple exit points!
   }
   return "hi";
  }
 }
 ]]>
     </example>
     </rule>

    <rule name="UnusedModifier"
    		since="1.02"
         message="Avoid modifiers which are implied by the context"
         class="net.sourceforge.pmd.rules.UnusedModifier"
          externalInfoUrl="http://pmd.sourceforge.net/rules/controversial.html#UnusedModifier">
     <description>
 Fields in interfaces are automatically public static final, and
 methods are public abstract.
 Classes or interfaces nested in an interface are automatically public
 and static (all nested interfaces are automatically static).
 For historical reasons, modifiers which are implied by the context
 are accepted by the compiler, but are superfluous.
     </description>
        <priority>3</priority>
     <example>
 <![CDATA[
public interface Foo {
 public abstract void bar(); // both abstract and public are ignored by the compiler
 public static final int X = 0; // public, static, and final all ignored
 public static class Bar {} // public, static ignored
 public static interface Baz {} // ditto
}
public class Bar {
 public static interface Baz {} // static ignored
}
 ]]>
     </example>
     </rule>

    <rule name="AssignmentInOperand"
      since="1.03"
      message="Avoid assignments in operands"
      class="net.sourceforge.pmd.rules.AssignmentInOperand"
          externalInfoUrl="http://pmd.sourceforge.net/rules/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 class Foo {
 public void bar() {
  int x = 2;
  if ((x = getX()) == 3) {
   System.out.println("3!");
  }
 }
 private int getX() {
  return 3;
 }
}
  ]]>
  </example>
</rule>

    <rule name="AtLeastOneConstructor"
    	since="1.04"
      message="Each class should declare at least one constructor"
      class="net.sourceforge.pmd.rules.XPathRule"
          externalInfoUrl="http://pmd.sourceforge.net/rules/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]) < 1)
]
	[@Interface='false']
]]>
          </value>
      </property>
  </properties>
  <example>
  <![CDATA[
public class Foo {
 // no constructor!  not good!
}
  ]]>
  </example>
</rule>

    <rule name="DontImportSun"
    	 since="1.5"
       message="Avoid importing anything from the 'sun.*' packages"
       class="net.sourceforge.pmd.rules.imports.DontImportSun"
          externalInfoUrl="http://pmd.sourceforge.net/rules/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.rules.SuspiciousOctalEscape"
          externalInfoUrl="http://pmd.sourceforge.net/rules/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 class Foo {
 public void foo() {
  // interpreted as octal 12, followed by character '8'
  System.out.println("suspicious: \128");
 }
}
]]>
      </example>
    </rule>

    <rule name="CallSuperInConstructor"
    		 since="3.0"
          message="It is a good practice to call super() in a constructor"
          class="net.sourceforge.pmd.rules.XPathRule"
          externalInfoUrl="http://pmd.sourceforge.net/rules/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"
    		 since="3.1"
          message="This statement may have some unnecessary parentheses"
          class="net.sourceforge.pmd.rules.XPathRule"
          externalInfoUrl="http://pmd.sourceforge.net/rules/controversial.html#UnnecessaryParentheses">
      <description>
Sometimes expressions are wrapped in unnecessary parentheses,
making them look like a function call.
      </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"
        since="3.4"
        message="Use explicit scoping instead of the default package private level"
        class="net.sourceforge.pmd.rules.XPathRule"
          externalInfoUrl="http://pmd.sourceforge.net/rules/controversial.html#DefaultPackage">
        <description>
Use explicit scoping instead of the default package private level.
        </description>
        <priority>3</priority>
        <properties>
            <property name="xpath">
                <value><![CDATA[
//ClassOrInterfaceDeclaration[@Interface='false']
/ClassOrInterfaceBody
/ClassOrInterfaceBodyDeclaration
[
FieldDeclaration[@PackagePrivate='true']
or MethodDeclaration[@PackagePrivate='true']
]
                ]]></value>
            </property>
        </properties>
    </rule>

    <rule name="BooleanInversion"
          since="3.5"
          message="Use bitwise inversion to invert boolean values"
          class="net.sourceforge.pmd.rules.XPathRule"
          externalInfoUrl="http://pmd.sourceforge.net/rules/controversial.html#BooleanInversion">
      <description>
Use bitwise inversion to invert boolean values - it's the fastest way to do this.
See http://www.javaspecialists.co.za/archive/newsletter.do?issue=042&amp;locale=en_US for specific details
      </description>
      <priority>3</priority>
      <properties>
          <property name="xpath">
              <value>
    <![CDATA[
//AssignmentOperator[@Image="="]/../Expression/UnaryExpressionNotPlusMinus[@Image="!"]
]]>
             </value>
          </property>
      </properties>
      <example>
  <![CDATA[
public class Foo {
 public void main(bar) {
  boolean b = true;
  b = !b; // slow
  b ^= true; // fast
 }
}
]]>
      </example>
    </rule>

    <rule name="DataflowAnomalyAnalysis"
    		  since="3.9"
              message="Found ''{0}''-anomaly for variable ''{1}'' (lines ''{2}''-''{3}'')."
              class="net.sourceforge.pmd.dfa.DaaRule"
              dfa="true"
              externalInfoUrl="http://pmd.sourceforge.net/rules/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>
          <properties>
            <property name="maxviolations" value="100" description="The maximum number of violations per class."/>
            <property name="maxpaths" value="1000" description="The maximum number of checked paths per method. A lower value will increase the performance of the rule but may decrease the number of found anomalies."/>
          </properties>
          <example>
<![CDATA[
public class Foo {
    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"
	      since="4.1"
        	class="net.sourceforge.pmd.rules.XPathRule"
        	message="Avoid using final local variables, turn them into fields"
        	externalInfoUrl="http://pmd.sourceforge.net/rules/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']
	             ]]></value>
	            </property>
	        </properties>
	        <example><![CDATA[
public class MyClass {
    public void foo() {
        final String finalLocalVariable;
    }
}
	     ]]></example>
    </rule>

	<rule
        name="AvoidUsingShortType"
        since="4.1"
        message="Do not use the short type"
        class="net.sourceforge.pmd.rules.XPathRule"
    	externalInfoUrl="http://pmd.sourceforge.net/rules/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 caculation
            and convert the int back to a short. So, the use of the 'short' type may have a greater impact than memory usage.
            ]]>
        </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"
        since="4.1"
        class="net.sourceforge.pmd.rules.XPathRule"
        message="Use of modifier volatile is not recommended."
    	externalInfoUrl="http://pmd.sourceforge.net/rules/controversial.html#AvoidUsingVolatile">

        <description>
            <![CDATA[
Use of the keyword 'volatile' is general 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 var;

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


	<rule
		name="AvoidUsingNativeCode"
		  since="4.1"
        message="The use of native code is not recommended."
        class="net.sourceforge.pmd.rules.XPathRule"
        externalInfoUrl="http://pmd.sourceforge.net/rules/controversial.html#AvoidUsingNativeCode">
        <description>
            <![CDATA[
                As JVM and Java language offer already many help in creating application, it should be
                very rare to have to rely on non-java code. Even though, it is rare to actually have to
                use Java Native Interface (JNI). As the use of JNI make application less portable, and
                harder to maintain, it is not recommended.
            ]]>
        </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"
		  since="4.1"
        message="You should modify visibility of class or methods using getDeclaredConstructors(), getDeclaredConstructor(Class[]), setAccessible() or PrivilegedAction."
        class="net.sourceforge.pmd.rules.XPathRule"
        externalInfoUrl="http://pmd.sourceforge.net/rules/controversial.html#AvoidAccessibilityAlteration">
        <description>
            <![CDATA[
            Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(),
            as the interface PrivilegedAction, allow to alter, at runtime, the visilibilty of variable, classes, or
            methods, even if they are private. Obviously, no one should do so, as such behavior is against everything
            encapsulation principal stands for.
            ]]>
        </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"
			    since="4.2"
	        	message="Do not explicitly trigger a garbage collection."
	        	class="net.sourceforge.pmd.rules.XPathRule"
	        	externalInfoUrl="http://pmd.sourceforge.net/rules/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>

</ruleset>


