org.sonar.plugins.groovy.rules.xml Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sonar-groovy-plugin Show documentation
Show all versions of sonar-groovy-plugin Show documentation
Enables scanning of Groovy source files.
The newest version!
<!-- Generated using CodeNarc 0.25.2 --> <rules> <!-- basic rules --> <rule> <key>org.codenarc.rule.basic.BigDecimalInstantiationRule</key> <severity>MINOR</severity> <name><![CDATA[Big Decimal Instantiation]]></name> <internalKey><![CDATA[BigDecimalInstantiation]]></internalKey> <description><![CDATA[<p>Checks for calls to the <code>java.math.BigDecimal</code> constructors that take a <code>double</code> value as the first parameter. As described in the <code>BigDecimal</code> javadoc, the results from these constructors can be somewhat unpredictable, and their use is generally not recommended. This is because some numbers, such as 0.1, cannot be represented exactly as a <code>double</code>. </p> <p>For instance, executing <code>println new BigDecimal(0.1)</code> prints out <code>0.1000000000000000055511151231257827021181583404541015625</code>. </p> <p>Here is an example of code that produces a violation: </p> <pre> def b1 = new BigDecimal(0.1) // violation def b2 = new java.math.BigDecimal(23.45d) // violation </pre> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.basic.ConstantIfExpressionRule</key> <severity>MINOR</severity> <name><![CDATA[Constant If Expression]]></name> <internalKey><![CDATA[ConstantIfExpression]]></internalKey> <description><![CDATA[<p>Checks for <if> statements with a constant value for the <if> boolean expression, such as <code>true</code>, <code>false</code>, <code>null</code>, or a literal constant value. These <if> statements can be simplified or avoided altogether. Examples of violations include: </p> <pre> if (true) { .. } if (false) { .. } if (Boolean.TRUE) { .. } if (Boolean.FALSE) { .. } if (null) { .. } if (0) { .. } if (99.7) { .. } if ("") { .. } if ("abc") { .. } if ([:]) { .. } if ([a:123, b:456]) { .. } if ([a, b, c]) { .. } </pre> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.basic.ConstantTernaryExpressionRule</key> <severity>MINOR</severity> <name><![CDATA[Constant Ternary Expression]]></name> <internalKey><![CDATA[ConstantTernaryExpression]]></internalKey> <description><![CDATA[<p>Checks for ternary expressions with a constant value for the boolean expression, such as <code>true</code>, <code>false</code>, <code>null</code>, or a literal constant value. Examples of violations include: </p> <pre> true ? x : y false ? x : y Boolean.TRUE ? x : y Boolean.FALSE ? x : y null ? x : y 0 ? x : y 99.7 ? x : y "" ? x : y "abc" ? x : y [:] ? x : y [a:123, b:456] ? x : y [a, b, c] ? x : y </pre> <pre> true ?: y null ?: y 99.7 ?: y "abc" ?: y [:] ?: y [a, b, c] ?: y </pre> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.basic.EmptyCatchBlockRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Catch Block]]></name> <internalKey><![CDATA[EmptyCatchBlock]]></internalKey> <description><![CDATA[<p>Checks for empty <catch> blocks. In most cases, exceptions should not be caught and ignored (swallowed). </p> <p>The rule has a property named <code>ignoreRegex</code> that defaults to the value 'ignore|ignored'. If the name of the exception matches this regex then no violations are produced. </p> <p>Here is an example of code that produces a violation: </p> <pre> def myMethod() { try { doSomething } catch(MyException e) { //violation // should do something here } } def myMethod() { try { doSomething } catch(MyException ignored) { //no violations because the parameter name is ignored } } </pre> ]]></description> <tag>unused</tag> <param> <key>ignoreRegex</key> <description><![CDATA[Regular expression - exception parameter names matching this regular expression are ignored and no volations are produced. ]]></description> <defaultValue>ignore|ignored</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.basic.EmptyElseBlockRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Else Block]]></name> <internalKey><![CDATA[EmptyElseBlock]]></internalKey> <description><![CDATA[<p>Checks for empty <else> blocks. Empty <else> blocks are confusing and serve no purpose. </p> <p>Here is an example of code that produces a violation: </p> <pre> def myMethod() { if (x==23) { println 'ok' } else { // empty } } </pre> ]]></description> <tag>unused</tag> </rule> <rule> <key>org.codenarc.rule.basic.EmptyFinallyBlockRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Finally Block]]></name> <internalKey><![CDATA[EmptyFinallyBlock]]></internalKey> <description><![CDATA[<p>Checks for empty <finally> blocks. Empty <finally> blocks are confusing and serve no purpose. </p> <p>Here is an example of code that produces a violation: </p> <pre> def myMethod() { try { doSomething() } finally { // empty } } </pre> ]]></description> <tag>unused</tag> </rule> <rule> <key>org.codenarc.rule.basic.EmptyForStatementRule</key> <severity>MINOR</severity> <name><![CDATA[Empty For Statement]]></name> <internalKey><![CDATA[EmptyForStatement]]></internalKey> <description><![CDATA[<p>Checks for empty <for> blocks. Empty <for> statements are confusing and serve no purpose. </p> <p>Here is an example of code that produces a violation: </p> <pre> def myMethod() { for (int i=0; i < 23; i++) { // empty } } </pre> ]]></description> <tag>unused</tag> </rule> <rule> <key>org.codenarc.rule.basic.EmptyIfStatementRule</key> <severity>MINOR</severity> <name><![CDATA[Empty If Statement]]></name> <internalKey><![CDATA[EmptyIfStatement]]></internalKey> <description><![CDATA[<p>Checks for empty <if> statements. Empty <if> statements are confusing and serve no purpose. </p> <p>Here is an example of code that produces a violation: </p> <pre> def myMethod() { if (x==23) { // empty } } </pre> ]]></description> <tag>unused</tag> </rule> <rule> <key>org.codenarc.rule.basic.EmptySwitchStatementRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Switch Statement]]></name> <internalKey><![CDATA[EmptySwitchStatement]]></internalKey> <description><![CDATA[<p>Checks for empty <switch> statements. Empty <switch> statements are confusing and serve no purpose. </p> <p>Here is an example of code that produces a violation: </p> <pre> def myMethod() { switch(myVariable) { // empty } } </pre> ]]></description> <tag>unused</tag> </rule> <rule> <key>org.codenarc.rule.basic.EmptySynchronizedStatementRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Synchronized Statement]]></name> <internalKey><![CDATA[EmptySynchronizedStatement]]></internalKey> <description><![CDATA[<p>Checks for empty <synchronized> statements. Empty <synchronized> statements are confusing and serve no purpose. </p> <p>Here is an example of code that produces a violation: </p> <pre> class MyClass { def myMethod() { synchronized(lock) { } } } </pre> ]]></description> <tag>unused</tag> </rule> <rule> <key>org.codenarc.rule.basic.EmptyTryBlockRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Try Block]]></name> <internalKey><![CDATA[EmptyTryBlock]]></internalKey> <description><![CDATA[<p>Checks for empty <try> blocks. Empty <try> blocks are confusing and serve no purpose. </p> <p>Here is an example of code that produces a violation: </p> <pre> def myMethod() { try { // empty } catch(MyException e) { e.printStackTrace() } } </pre> ]]></description> <tag>unused</tag> </rule> <rule> <key>org.codenarc.rule.basic.EmptyWhileStatementRule</key> <severity>MINOR</severity> <name><![CDATA[Empty While Statement]]></name> <internalKey><![CDATA[EmptyWhileStatement]]></internalKey> <description><![CDATA[<p>Checks for empty <while> statements. Empty <while> statements are confusing and serve no purpose. </p> <p>Here is an example of code that produces a violation: </p> <pre> def myMethod() { while (!stopped) { // empty } } </pre> ]]></description> <tag>unused</tag> </rule> <rule> <key>org.codenarc.rule.basic.EqualsAndHashCodeRule</key> <severity>MINOR</severity> <name><![CDATA[Equals And Hash Code]]></name> <internalKey><![CDATA[EqualsAndHashCode]]></internalKey> <description><![CDATA[<p>Checks that if either the <code>boolean equals(Object)</code> or the <code>int hashCode()</code> methods are overridden within a class, then both must be overridden. </p> <p>Here is an example of code that produces a violation: </p> <pre> class MyClass { boolean equals(Object object) { // do something } } </pre> <pre> class MyClass { int hashCode() { return 0 } } </pre> ]]></description> <tag>pitfall</tag> </rule> <rule> <key>org.codenarc.rule.basic.ReturnFromFinallyBlockRule</key> <severity>MINOR</severity> <name><![CDATA[Return From Finally Block]]></name> <internalKey><![CDATA[ReturnFromFinallyBlock]]></internalKey> <description><![CDATA[<p>Checks for a return from within a <finally> block. Returning from a <finally> block is confusing and can hide the original exception. </p> <p>Here is an example of code that produces a violation: </p> <pre> int myMethod() { try { doSomething() return 0 } catch(Exception e) { return -1 } finally { return 99 // violation } } </pre> ]]></description> <tag>error-handling</tag> </rule> <rule> <key>org.codenarc.rule.basic.ThrowExceptionFromFinallyBlockRule</key> <severity>MINOR</severity> <name><![CDATA[Throw Exception From Finally Block]]></name> <internalKey><![CDATA[ThrowExceptionFromFinallyBlock]]></internalKey> <description><![CDATA[<p>Checks for throwing an exception from within a <finally> block. Throwing an exception from a <finally> block is confusing and can hide the original exception. </p> <p>Here is an example of code that produces a violation: </p> <pre> int myMethod() { try { doSomething() throw new Exception() } finally { println 'finally' throw new Exception() // violation } } </pre> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.basic.DeadCodeRule</key> <severity>MINOR</severity> <name><![CDATA[Dead Code]]></name> <internalKey><![CDATA[DeadCode]]></internalKey> <description><![CDATA[<p>Dead code appears after a <code>return</code> statement or an exception is thrown. If code appears after one of these statements then it will never be executed and can be safely deleted. </p> ]]></description> <tag>unused</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.basic.DoubleNegativeRule</key> <severity>MINOR</severity> <name><![CDATA[Double Negative]]></name> <internalKey><![CDATA[DoubleNegative]]></internalKey> <description><![CDATA[<p>There is no point in using a double negative, it is always positive. For instance <code>!!x</code> can always be simplified to <code>x</code>. And <code>!(!x)</code> can as well. </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.basic.DuplicateCaseStatementRule</key> <severity>MINOR</severity> <name><![CDATA[Duplicate Case Statement]]></name> <internalKey><![CDATA[DuplicateCaseStatement]]></internalKey> <description><![CDATA[<p>Check for duplicate <code>case</code> statements in a <code>switch</code> block, such as two equal integers or strings. Here are some examples of code that produces violations: </p> <pre> switch( 0 ) { case 1: break; case 2: break; case 2: break; // violation } switch( "test" ) { case "$a": break; case "$a": break; // ok; only flags constant values (not GStrings) case "ab": break; case "ab": break; // violation case "abc": break; } </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.basic.RemoveAllOnSelfRule</key> <severity>MINOR</severity> <name><![CDATA[Remove All On Self]]></name> <internalKey><![CDATA[RemoveAllOnSelf]]></internalKey> <description><![CDATA[<p>Don't use <code>removeAll</code> to clear a collection. If you want to remove all elements from a collection <code>c</code>, use <code>c.clear</code>, not <code>c.removeAll(c)</code>. Calling <code>c.removeAll(c)</code> to clear a collection is less clear, susceptible to errors from typos, less efficient and for some collections, might throw a <code>ConcurrentModificationException</code>. </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.basic.ExplicitGarbageCollectionRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Garbage Collection]]></name> <internalKey><![CDATA[ExplicitGarbageCollection]]></internalKey> <description><![CDATA[<p>Calls to <code>System.gc()</code>, <code>Runtime.getRuntime().gc()</code>, and <code>System.runFinalization()</code> are not advised. Code should have the same behavior whether the garbage collection is disabled using the option <code>-Xdisableexplicitgc</code> 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. </p> ]]></description> <tag>unpredictable</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.basic.AssignmentInConditionalRule</key> <severity>MINOR</severity> <name><![CDATA[Assignment In Conditional]]></name> <internalKey><![CDATA[AssignmentInConditional]]></internalKey> <description><![CDATA[<p>An assignment operator (=) was used in a conditional test. This is usually a typo, and the comparison operator (==) was intended. </p> <p>Example of violations: </p> <pre> if ((value = true)) { // should be == } while (value = true) { // should be == } (value = true) ? x : y (value = true) ?: x // the following code has no violations if (value == true) { } value == true ? x : y value == true ?: x </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.basic.BooleanGetBooleanRule</key> <severity>MINOR</severity> <name><![CDATA[Boolean Get Boolean]]></name> <internalKey><![CDATA[BooleanGetBoolean]]></internalKey> <description><![CDATA[<p>This rule catches usages of java.lang.Boolean.getBoolean(String) which reads a boolean from the System properties. It is often mistakenly used to attempt to read user input or parse a String into a boolean. It is a poor piece of API to use; replace it with System.properties['prop̈́']. </p> <p>Example of violations: </p> <pre> // produces violation Boolean.getBoolean(value) // zero or two parameters is OK, must be different method Boolean.getBoolean(value, 1) Boolean.getBoolean() </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.basic.BrokenOddnessCheckRule</key> <severity>MINOR</severity> <name><![CDATA[Broken Oddness Check]]></name> <internalKey><![CDATA[BrokenOddnessCheck]]></internalKey> <description><![CDATA[<p>The code uses <code>x % 2 == 1</code> to check to see if a value is odd, but this won't work for negative numbers (e.g., <code>(-5) % 2 == -1)</code>. If this code is intending to check for oddness, consider using <code>x & 1 == 1</code>, or <code> x % 2 != 0</code>. </p> <p>Examples: </p> <pre> if (x % 2 == 1) { } // violation if (method() % 2 == 1) { } // violation if (x & 1 == 1) { } // OK if (x % 2 != 0) { } // OK </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.basic.EmptyInstanceInitializerRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Instance Initializer]]></name> <internalKey><![CDATA[EmptyInstanceInitializer]]></internalKey> <description><![CDATA[<p>An empty class instance initializer was found. It is safe to remove it. Example: </p> <pre> class MyClass { { } // empty instance initializer, not a closure } </pre> ]]></description> <tag>unused</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.basic.EmptyMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Method]]></name> <internalKey><![CDATA[EmptyMethod]]></internalKey> <description><![CDATA[<p>A method was found without an implementation. If the method is overriding or implementing a parent method, then mark it with the <code>@Override</code> annotation. This rule should not be used with Java 5 code because you cannot put <code>@Override</code> on a method implementing an interface. Use with Java 6 and higher. </p> <p>Example of violations: </p> <pre> class MyClass { // violation, empty method public void method1() {} // violation, empty method def method2() {} // OK because of @Override @Override public void method3() {} } abstract class MyBaseClass { // OK, handled by EmptyMethodInAbstractClass Rule public void method() {} } </pre> ]]></description> <tag>unused</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.basic.EmptyStaticInitializerRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Static Initializer]]></name> <internalKey><![CDATA[EmptyStaticInitializer]]></internalKey> <description><![CDATA[<p>An empty static initializer was found. It is safe to remove it. Example: </p> <pre> class MyClass { static { } } </pre> ]]></description> <tag>unused</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.basic.IntegerGetIntegerRule</key> <severity>MINOR</severity> <name><![CDATA[Integer Get Integer]]></name> <internalKey><![CDATA[IntegerGetInteger]]></internalKey> <description><![CDATA[<p>This rule catches usages of java.lang.Integer.getInteger(String, ...) which reads an Integer from the System properties. It is often mistakenly used to attempt to read user input or parse a String into an Integer. It is a poor piece of API to use; replace it with System.properties['prop']. </p> <p>Example of violations: </p> <pre> // violations Integer.getInteger(value) Integer.getInteger(value, radix) // zero or more than 2 parameters is OK, must be different method Integer.getInteger() Integer.getInteger(value, radix, locale) </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.basic.DuplicateMapKeyRule</key> <severity>MINOR</severity> <name><![CDATA[Duplicate Map Key]]></name> <internalKey><![CDATA[DuplicateMapKey]]></internalKey> <description><![CDATA[<p>A <Map> literal is created with duplicated key. The map entry will be overwritten. </p> <p>Example of violations: </p> <pre> def var1 = [a:1, a:2, b:3] //violation def var2 = [1:1, 1:2, 2:3] //violation def var3 = ["a":1, "a":2, "b":3] //violation // these are OK def var4 = [a:1, b:1, c:1] def var5 = [1:1, 2:1, 3:1] def var6 = ["a":1, "b":1, "c":1] </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.basic.DuplicateSetValueRule</key> <severity>MINOR</severity> <name><![CDATA[Duplicate Set Value]]></name> <internalKey><![CDATA[DuplicateSetValue]]></internalKey> <description><![CDATA[<p>A <Set> literal is created with duplicate constant value. A set cannot contain two elements with the same value. </p> <p>Example of violations: </p> <pre> def a = [1, 2, 2, 4] as Set def b = [1, 2, 2, 4] as HashSet def c = [1, 2, 2, 4] as SortedSet def d = [1, 2, 2, 4] as FooSet def e = ['1', '2', '2', '4'] as Set def f = ['1', '2', '2', '4'] as HashSet def g = ['1', '2', '2', '4'] as SortedSet def h = ['1', '2', '2', '4'] as FooSet // these are OK def a = [1, 2, 3, 4] as Set def b = ['1', '2', '3', '4'] as Set def c = [1, '1'] as Set </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.basic.EqualsOverloadedRule</key> <severity>MINOR</severity> <name><![CDATA[Equals Overloaded]]></name> <internalKey><![CDATA[EqualsOverloaded]]></internalKey> <description><![CDATA[<p>The class has an <code>equals</code> method, but the parameter of the method is not of type <code>Object</code>. It is not overriding <code>equals</code> but instead overloading it. </p> <p>Example of violations: </p> <pre> class Object1 { //parameter should be Object not String boolean equals(String other) { true } } class Object2 { // Overloading equals() with 2 parameters is just mean boolean equals(Object other, String other2) { true } } class Object3 { // a no-arg equals()? What is this supposed to do? boolean equals() { true } } // all of these are OK and do not cause violations class Object4 { boolean equals(Object other) { true } } @SuppressWarnings('EqualsOverloaded') class Object5 { boolean equals(String other) { true } } class Object6 { boolean equals(java.lang.Object other) { true } } class Object7 { boolean equals(other) { true } } </pre> ]]></description> <tag>pitfall</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.basic.ForLoopShouldBeWhileLoopRule</key> <severity>MAJOR</severity> <name><![CDATA[For Loop Should Be While Loop]]></name> <internalKey><![CDATA[ForLoopShouldBeWhileLoop]]></internalKey> <description><![CDATA[<p>A <code>for</code> loop without an init and update statement can be simplified to a <code>while</code> loop. </p> <p>Example of violations: </p> <pre> int i = 0; for(; i < 5;) { // Violation println i++ } // These are OK for(i in [1,2]) // OK println i for(int i = 0; i<5;) // OK println i++ int i = 0; for(; i < 5; i++) // OK println i for (Plan p : plans) { // OK println "Plan=$p" } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.basic.ClassForNameRule</key> <severity>MINOR</severity> <name><![CDATA[Class For Name]]></name> <internalKey><![CDATA[ClassForName]]></internalKey> <description><![CDATA[<p>Using <code>Class.forName(...)</code> is a common way to add dynamic behavior to a system. However, using this method can cause resource leaks because the classes can be pinned in memory for long periods of time. If you're forced to do dynamic class loading then use ClassLoader.loadClass instead. All variations of the <code>Class.forName(...)</code> method suffer from the same problem. </p> <p>For more information see these links: </p> <p>* <a>http://blog.bjhargrave.com/2007/09/classforname-caches-defined-class-in.html</a> </p> <p>* <a>http://www.osgi.org/blog/2011/05/what-you-should-know-about-class.html</a> </p> Example of violations: </p> <pre> Class.forName('SomeClassName') Class.forName(aClassName, true, aClassLoader) </pre> ]]></description> <tag>leak</tag> <tag>owasp-a1</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.basic.ComparisonOfTwoConstantsRule</key> <severity>MINOR</severity> <name><![CDATA[Comparison Of Two Constants]]></name> <internalKey><![CDATA[ComparisonOfTwoConstants]]></internalKey> <description><![CDATA[<p>Checks for expressions where a <comparison operator> or <code>equals()</code> or <code>compareTo()</code> is used to compare two constants to each other or two literals that contain only constant values. </p> <p>Here are examples of code that produces a violation: </p> <pre> 23 == 67 // violation Boolean.FALSE != false // violation 23 < 88 // violation 0.17 <= 0.99 // violation "abc" > "ddd" // violation [Boolean.FALSE] >= [27] // violation [a:1] <=> [a:2] // violation [1,2].equals([3,4]) // violation [a:123, b:true].equals(['a':222, b:Boolean.FALSE]) // violation [a:123, b:456].compareTo([a:222, b:567] // violation [a:false, b:true].compareTo(['a':34.5, b:Boolean.TRUE] // violation </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.basic.ComparisonWithSelfRule</key> <severity>MINOR</severity> <name><![CDATA[Comparison With Self]]></name> <internalKey><![CDATA[ComparisonWithSelf]]></internalKey> <description><![CDATA[<p>Checks for expressions where a <comparison operator> or <code>equals()</code> or <code>compareTo()</code> is used to compare a variable to itself, e.g.: <code>x == x, x != x, x \<=\> x, x \< x, x \>= x, x.equals(x) or x.compareTo(x)</code>, where <code>x</code> is a variable. </p> <p>Here are examples of code that produces a violation: </p> <pre> if (x == x) { } // violation if (x != x) { } // violation while (x < x) { } // violation if (x <= x) { } // violation while (x > x) { } // violation if (x >= x) { } // violation def c = (x <=> x) { } // violation println isReady = x.equals(x) // violation println x.compareTo(x) // violation </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.basic.BitwiseOperatorInConditionalRule</key> <severity>MINOR</severity> <name><![CDATA[Bitwise Operator In Conditional]]></name> <internalKey><![CDATA[BitwiseOperatorInConditional]]></internalKey> <description><![CDATA[<p>Checks for bitwise operations in conditionals. For instance, the condition <code>if (a | b)</code> is almost always a mistake and should be <code>if (a || b)</code>. If you need to do a bitwise operation then it is best practice to extract a temp variable. </p> <p>Example of violations: </p> <pre> if (a | b) { } if (a & b) { } </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.basic.HardCodedWindowsFileSeparatorRule</key> <severity>MINOR</severity> <name><![CDATA[Hard Coded Windows File Separator]]></name> <internalKey><![CDATA[HardCodedWindowsFileSeparator]]></internalKey> <description><![CDATA[<p>This rule finds usages of a Windows file separator within the constructor call of a File object. It is better to use the Unix file separator or use the File.separator constant. </p> <p>Example of violations: </p> <pre> new File('.\\foo\\') new File('c:\\dir') new File('../foo\\') </pre> ]]></description> <tag>pitfall</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.basic.RandomDoubleCoercedToZeroRule</key> <severity>MINOR</severity> <name><![CDATA[Random Double Coerced To Zero]]></name> <internalKey><![CDATA[RandomDoubleCoercedToZero]]></internalKey> <description><![CDATA[<p>The Math.random() method returns a double result greater than or equal to 0.0 and less than 1.0. If you coerce this result into an Integer, Long, int, or long then it is coerced to zero. Casting the result to int, or assigning it to an int field is probably a bug. </p> <p>Example of violations: </p> <pre> (int) Math.random() (Integer) Math.random() int x = Math.random() Integer y = Math.random() int m() { Math.random() } Integer m() { Math.random() } (Math.random()) as int (Math.random()) as Integer </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.basic.HardCodedWindowsRootDirectoryRule</key> <severity>MINOR</severity> <name><![CDATA[Hard Coded Windows Root Directory]]></name> <internalKey><![CDATA[HardCodedWindowsRootDirectory]]></internalKey> <description><![CDATA[<p>This rule find cases where a File object is constructed with a windows-based path. This is not portable across operating systems or different machines, and using the File.listRoots() method is a better alternative. </p> <p>Example of violations: </p> <pre> new File('c:\\') new File('c:\\dir') new File('E:\\dir') </pre> ]]></description> <tag>pitfall</tag> </rule> <!-- since 0.17 --> <rule> <key>org.codenarc.rule.basic.AssertWithinFinallyBlockRule</key> <severity>MINOR</severity> <name><![CDATA[Assert Within Finally Block]]></name> <internalKey><![CDATA[AssertWithinFinallyBlock]]></internalKey> <description><![CDATA[<p>Checks for <assert> statements within a <finally> block. An <assert> can throw an exception, hiding the original exception, if there is one. </p> <p>Here is an example of code that produces a violation: </p> <pre> int myMethod(int count) { try { doSomething() } finally { assert count > 0 // violation } } </pre> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.17 --> <rule> <key>org.codenarc.rule.basic.ConstantAssertExpressionRule</key> <severity>MAJOR</severity> <name><![CDATA[Constant Assert Expression]]></name> <internalKey><![CDATA[ConstantAssertExpression]]></internalKey> <description><![CDATA[<p>Checks for <assert> statements with a constant value for the <assert> boolean expression, such as <code>true</code>, <code>false</code>, <code>null</code>, or a literal constant value. These <assert> statements will always pass or always fail, depending on the constant/literal value. Examples of violations include: </p> <pre> assert true assert false, "assertion message" assert Boolean.TRUE assert Boolean.FALSE assert null assert 0 assert 99.7 assert "" assert "abc" assert [:] assert [a:123, b:456] assert [a, b, c] </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.17 --> <rule> <key>org.codenarc.rule.basic.BrokenNullCheckRule</key> <severity>MINOR</severity> <name><![CDATA[Broken Null Check]]></name> <internalKey><![CDATA[BrokenNullCheck]]></internalKey> <description><![CDATA[<p>Looks for faulty checks for <null> that can cause a <code>NullPointerException</code>. </p> <p>Examples: </p> <pre> if (name != null || name.length > 0) { } // violation if (name != null || name.length) { } // violation while (record == null && record.id < 10) { } // violation if (record == null && record.id && doStuff()) { } // violation def isNotValid = record == null && record.id < 10 // violation return record == null && !record.id // violation if (name != null || name.size() > 0) { } // violation if (string == null && string.equals("")) { } // violation def isValid = name != null || name.size() > 0 // violation return name != null || !name.size() // violation </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.basic.EmptyClassRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Class]]></name> <internalKey><![CDATA[EmptyClass]]></internalKey> <description><![CDATA[<p>Reports classes without methods, fields or properties. Why would you need a class like this? </p> <p>This rule ignores interfaces, abstract classes, enums, anonymous inner classes, subclasses (extends), and classes with annotations. </p> ]]></description> <tag>unused</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.basic.MultipleUnaryOperatorsRule</key> <severity>MINOR</severity> <name><![CDATA[Multiple Unary Operators]]></name> <internalKey><![CDATA[MultipleUnaryOperators]]></internalKey> <description><![CDATA[<p>Checks for multiple consecutive unary operators. These are confusing, and are likely typos and bugs. </p> <p>Example of violations: </p> <pre> int z = ~~2 // violation boolean b = !!true // violation boolean c = !!!false // 2 violations int j = -~7 // violation int k = +~8 // violation </pre> ]]></description> <tag>bug</tag> </rule> <!-- serialization rules --> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.serialization.SerialVersionUIDRule</key> <severity>MINOR</severity> <name><![CDATA[Serial Version UID]]></name> <internalKey><![CDATA[SerialVersionUID]]></internalKey> <description><![CDATA[<p> A <code>serialVersionUID</code> is normally intended to be used with Serialization. It needs to be of type <code>long</code>, <code>static</code>, and <code>final</code>. Also, it should be declared <code>private</code>. Providing no modifier creates a <Property> and Groovy generates a <getter>, which is probably not intended. </p> <p>From API javadoc for <code>java.io.Serializable</code>: <It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.> </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.serialization.SerializableClassMustDefineSerialVersionUIDRule</key> <severity>MINOR</severity> <name><![CDATA[Serializable Class Must Define Serial Version UID]]></name> <internalKey><![CDATA[SerializableClassMustDefineSerialVersionUID]]></internalKey> <description><![CDATA[<p>Classes that implement <code>Serializable</code> should define a <code>serialVersionUID</code>. Deserialization uses this number to ensure that a loaded class corresponds exactly to a serialized object. If you don't define serialVersionUID, the system will make one by hashing most of your class's features. Then if you change anything, the UID will change and Java won't let you reload old data. </p> <p>An example of a missing serialVersionUID: </p> <pre> class MyClass imlements Serializable { // missing serialVersionUID } </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.serialization.SerialPersistentFieldsRule</key> <severity>MINOR</severity> <name><![CDATA[Serial Persistent Fields]]></name> <internalKey><![CDATA[SerialPersistentFields]]></internalKey> <description><![CDATA[<p>To use a <code>Serializable</code> object's <code>serialPersistentFields</code> correctly, it must be declared <code>private</code>, <code>static</code>, and <code>final</code>. </p> <p>The Java Object Serialization Specification allows developers to manually define <code>Serializable</code> fields for a class by specifying them in the <code>serialPersistentFields</code> array. This feature will only work if <code>serialPersistentFields</code> is declared as <code>private</code>, <code>static</code>, and <code>final</code>. Also, specific to Groovy, the field must be of type <code>ObjectStreamField[]</code>, and cannot be <code>Object</code>. </p> <p>References: </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.serialization.EnumCustomSerializationIgnoredRule</key> <severity>MINOR</severity> <name><![CDATA[Enum Custom Serialization Ignored]]></name> <internalKey><![CDATA[EnumCustomSerializationIgnored]]></internalKey> <description><![CDATA[<p>Checks for enums that define <code>writeObject()</code> or <code>writeReplace()</code> methods, or declare <code>serialPersistentFields</code> or <code>serialVersionUID</code> fields, all of which are ignored for enums. </p> <p>From the javadoc for <code>ObjectOutputStream</code>: </p> <p><The process by which enum constants are serialized cannot be customized; any class-specific writeObject and writeReplace methods defined by enum types are ignored during serialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L.> </p> <p>Example of violations: </p> <pre> enum MyEnum { ONE, TWO, THREE private static final long serialVersionUID = 1234567L // violation private static final ObjectStreamField[] serialPersistentFields = // violation { new ObjectStreamField("name", String.class) } String name; Object writeReplace() throws ObjectStreamException { .. } // violation private void writeObject(ObjectOutputStream stream) { .. } // violation } </pre> ]]></description> <tag>bug</tag> </rule> <!-- braces rules --> <rule> <key>org.codenarc.rule.braces.IfStatementBracesRule</key> <severity>MINOR</severity> <name><![CDATA[If Statement Braces]]></name> <internalKey><![CDATA[IfStatementBraces]]></internalKey> <description><![CDATA[<p>Checks that <if> statements use braces, even for a single statement. </p> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.braces.ElseBlockBracesRule</key> <severity>MINOR</severity> <name><![CDATA[Else Block Braces]]></name> <internalKey><![CDATA[ElseBlockBraces]]></internalKey> <description><![CDATA[<p>Checks that <else> blocks use braces, even for a single statement. </p> <p>By default, braces are not required for an <else> if it is followed immediately by an <if>. Set the <bracesRequiredForElseIf> property to true to require braces is that situation as well. </p> ]]></description> <tag>bug</tag> <param> <key>bracesRequiredForElseIf</key> <description><![CDATA[Set to true to require braces for an <else> block followed immediately by an <if> statement. ]]></description> <defaultValue>false</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.braces.ForStatementBracesRule</key> <severity>MINOR</severity> <name><![CDATA[For Statement Braces]]></name> <internalKey><![CDATA[ForStatementBraces]]></internalKey> <description><![CDATA[<p>Checks that <for> statements use braces, even for a single statement. </p> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.braces.WhileStatementBracesRule</key> <severity>MINOR</severity> <name><![CDATA[While Statement Braces]]></name> <internalKey><![CDATA[WhileStatementBraces]]></internalKey> <description><![CDATA[<p>Checks that while statements use braces, even for a single statement. </p> ]]></description> <tag>bug</tag> </rule> <!-- concurrency rules --> <rule> <key>org.codenarc.rule.concurrency.NestedSynchronizationRule</key> <severity>MINOR</severity> <name><![CDATA[Nested Synchronization]]></name> <internalKey><![CDATA[NestedSynchronization]]></internalKey> <description><![CDATA[<p>This rule reports occurrences of nested <code>synchronized</code> statements. </p> <p>Nested <code>synchronized</code> statements should be avoided. Nested <code>synchronized</code> statements are either useless (if the lock objects are identical) or prone to deadlock. </p> <p>Note that a <closure> or an <anonymous inner class> carries its own context (scope). A <code>synchronized</code> statement within a <closure> or an <anonymous inner class> defined within an outer <code>synchronized</code> statement does not cause a violation (though nested <code>synchronized</code> statements within either of those will). </p> <p>Here is an example of code that produces a violation: </p> <pre> def myMethod() { synchronized(this) { // do something ... synchronized(this) { // do something else ... } } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <rule> <key>org.codenarc.rule.concurrency.SynchronizedMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Synchronized Method]]></name> <internalKey><![CDATA[SynchronizedMethod]]></internalKey> <description><![CDATA[<p>This rule reports uses of the <code>synchronized</code> keyword on methods. Synchronized methods are the same as synchronizing on 'this', which effectively make your synchronization policy public and modifiable by other objects. To avoid possibilities of deadlock, it is better to synchronize on internal objects. </p> <p>Here is an example of code that produces a violation: </p> <pre> synchronized def myMethod() { // do stuff ... } </pre> ]]></description> <tag>multi-threading</tag> </rule> <rule> <key>org.codenarc.rule.concurrency.SynchronizedOnThisRule</key> <severity>MINOR</severity> <name><![CDATA[Synchronized On This]]></name> <internalKey><![CDATA[SynchronizedOnThis]]></internalKey> <description><![CDATA[<p>This rule reports uses of the <code>synchronized</code> blocks where the synchronization reference is 'this'. Doing this effectively makes your synchronization policy public and modifiable by other objects. To avoid possibilities of deadlock, it is better to synchronize on internal objects. </p> <p>Here is an example of code that produces a violation: </p> <pre> def method3() { synchronized(this) { // do stuff ... } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <rule> <key>org.codenarc.rule.concurrency.SystemRunFinalizersOnExitRule</key> <severity>MINOR</severity> <name><![CDATA[System Run Finalizers On Exit]]></name> <internalKey><![CDATA[SystemRunFinalizersOnExit]]></internalKey> <description><![CDATA[<p>This rule reports uses of the <code>System.runFinalizersOnExit()</code> method. </p> <p>Method calls to <code>System.runFinalizersOnExit()</code> should not be allowed. This method is inherently non-thread-safe, may result in data corruption, deadlock, and may affect parts of the program far removed from it's call point. It is deprecated, and it's use strongly discouraged. </p> <p>Here is an example of code that produces a violation: </p> <pre> def method() { System.runFinalizersOnExit(true) } </pre> ]]></description> <tag>multi-threading</tag> </rule> <rule> <key>org.codenarc.rule.concurrency.ThreadGroupRule</key> <severity>MINOR</severity> <name><![CDATA[Thread Group]]></name> <internalKey><![CDATA[ThreadGroup]]></internalKey> <description><![CDATA[<p>Avoid using <code>ThreadGroup</code>; although it is intended to be used in a threaded environment it contains methods that are not thread safe. </p> <p>Here is an example of code that produces a violation: </p> <pre> new ThreadGroup("...") new ThreadGroup(tg, "my thread group") Thread.currentThread().getThreadGroup() System.getSecurityManager().getThreadGroup() </pre> ]]></description> <tag>multi-threading</tag> </rule> <rule> <key>org.codenarc.rule.concurrency.ThreadLocalNotStaticFinalRule</key> <severity>MINOR</severity> <name><![CDATA[Thread Local Not Static Final]]></name> <internalKey><![CDATA[ThreadLocalNotStaticFinal]]></internalKey> <description><![CDATA[<p>This rule reports definition of the <code>ThreadLocal</code> fields that are not <code>static</code> and <code>final</code>. </p> <p><ThreadLocal> fields should be <code>static</code> and <code>final</code>. In the most common case a <code>java.lang.ThreadLocal</code> instance associates state with a thread. A non-<code>static</code> non-<code>final</code> <code>java.lang.ThreadLocal</code> field associates state with an instance-thread combination. This is seldom necessary and often a bug which can cause memory leaks and possibly incorrect behavior. </p> <p>Here is an example of code that produces a violation: </p> <pre> private static ThreadLocal local1 = new ThreadLocal() private final ThreadLocal local2 = new ThreadLocal() protected ThreadLocal local3 = new ThreadLocal() ThreadLocal local4 = new ThreadLocal() </pre> ]]></description> <tag>multi-threading</tag> </rule> <rule> <key>org.codenarc.rule.concurrency.ThreadYieldRule</key> <severity>MINOR</severity> <name><![CDATA[Thread Yield]]></name> <internalKey><![CDATA[ThreadYield]]></internalKey> <description><![CDATA[<p>This rule reports uses of the <code>Thread.yield()</code> method. </p> <p>Method calls to <code>Thread.yield()</code> should not be allowed. This method has no useful guaranteed semantics, and is often used by inexperienced programmers to mask race conditions. </p> <p>Here is an example of code that produces a violation: </p> <pre> def method() { Thread.yield() } </pre> ]]></description> <tag>multi-threading</tag> </rule> <rule> <key>org.codenarc.rule.concurrency.VolatileLongOrDoubleFieldRule</key> <severity>MINOR</severity> <name><![CDATA[Volatile Long Or Double Field]]></name> <internalKey><![CDATA[VolatileLongOrDoubleField]]></internalKey> <description><![CDATA[<p>This rule reports on <code>long</code> or <code>double</code> fields that are declared <code>volatile</code>. </p> <p>Long or double fields should not be declared as <code>volatile</code>. Java specifies that reads and writes from such fields are atomic, but many JVM's have violated this specification. Unless you are certain of your JVM, it is better to synchronize access to such fields rather than declare them <code>volatile</code>. This rule flags fields marked <code>volatile</code> when their type is <code>double</code> or <code>long</code> or the name of their type is "Double" or "Long". </p> <p>Here is an example of code that produces a violation: </p> <pre> def method() { private volatile double d private volatile long f } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.concurrency.SynchronizedOnGetClassRule</key> <severity>MINOR</severity> <name><![CDATA[Synchronized On Get Class]]></name> <internalKey><![CDATA[SynchronizedOnGetClass]]></internalKey> <description><![CDATA[<p>Checks for synchronization on <code>getClass()</code> rather than class literal. This instance method synchronizes on <code>this.getClass()</code>. If this class is subclassed, subclasses will synchronize on the class object for the subclass, which isn't likely what was intended. </p> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.concurrency.UseOfNotifyMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Use Of Notify Method]]></name> <internalKey><![CDATA[UseOfNotifyMethod]]></internalKey> <description><![CDATA[<p>Checks for code that calls <code>notify()</code> rather than <code>notifyAll()</code>. Java monitors are often used for multiple conditions. Calling <code>notify()</code> only wakes up one thread, meaning that the awakened thread might not be the one waiting for the condition that the caller just satisfied. </p> <p>Also see <a href="http://www.javaconcurrencyinpractice.com/"><code>Java_Concurrency_in_Practice</code></a>, Brian Goetz, p 303. </p> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.BusyWaitRule</key> <severity>MINOR</severity> <name><![CDATA[Busy Wait]]></name> <internalKey><![CDATA[BusyWait]]></internalKey> <description><![CDATA[<p>Busy waiting (forcing a <code>Thread.sleep()</code> while waiting on a condition) should be avoided. Prefer using the gate and barrier objects in the <code>java.util.concurrent</code> package. </p> <p>Example of violations: </p> <pre> while (x) { Thread.sleep(1000) } while (x) { Thread.sleep(1000) { /* interruption handler */} } for (int x = 10; x; x--) { sleep(1000) // sleep is added to Object in Groovy } // here is the proper way to wait: countDownLatch.await() // this is weird code to write, but does not cause a violation for (def x : collections) { sleep(1000) } while (x) { // you should use a lock here, but technically you are // not just busy waiting because you are doing other work doSomething() sleep(1000) } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.DoubleCheckedLockingRule</key> <severity>MINOR</severity> <name><![CDATA[Double Checked Locking]]></name> <internalKey><![CDATA[DoubleCheckedLocking]]></internalKey> <description><![CDATA[<p>This rule detects double checked locking, where a 'lock hint' is tested for null before initializing an object within a synchronized block. Double checked locking does not guarantee correctness and is an anti-pattern. </p> <p>A full explanation of why double checked locking is broken in Java is available on Wikipedia: <a>http://en.wikipedia.org/wiki/Double-checked_locking</a> </p> <p>Example of violations: </p> <pre> if (object == null) { synchronized(this) { if (object == null) { // createObject() could be called twice depending // on the Thread Scheduler. object = createObject() } } } // there are several idioms to fix this problem. def result = object; if (result == null) { synchronized(this) { result = object; if (result == null) object = result = createObject() } } // and a better solution for a singleton: class myClass { private static class ObjectHolder { public static Object object = createObject() } public static Object getObject() { return ObjectHolder.object; } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.InconsistentPropertyLockingRule</key> <severity>MINOR</severity> <name><![CDATA[Inconsistent Property Locking]]></name> <internalKey><![CDATA[InconsistentPropertyLocking]]></internalKey> <description><![CDATA[<p>Class contains similarly-named get and set methods where one method of the pair is marked either @WithReadLock or @WithWriteLock and the other is not locked at all. This may result in incorrect behavior at runtime, as callers of the get and set methods will not necessarily lock correctly and my see an inconsistent state for the object. The get and set method should both be guarded by @WithReadLock/@WithWriteLock or neither should be guarded. </p> <p>Example of violations: </p> <pre> class Person { String name Date birthday boolean deceased boolean parent @WithWriteLock setName(String name) { this.name = name } // violation, get method should be locked String getName() { name } // violation, set method should be locked void setBirthday(Date birthday) { this.birthday = birthday } @WithReadLock String getBirthday() { birthday } // violation, set method should be locked void setDeceased(boolean deceased) { this.deceased = deceased } @WithReadLock boolean isDeceased() { deceased } @WithWriteLock void setParent(boolean parent) { this.parent = parent } // violation, get method should be locked boolean isParent() { parent } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.InconsistentPropertySynchronizationRule</key> <severity>MINOR</severity> <name><![CDATA[Inconsistent Property Synchronization]]></name> <internalKey><![CDATA[InconsistentPropertySynchronization]]></internalKey> <description><![CDATA[<p>Class contains similarly-named get and set methods where the set method is synchronized and the get method is not, or the get method is synchronized and the set method is not. This may result in incorrect behavior at runtime, as callers of the get and set methods will not necessarily see a consistent state for the object. The get and set method should both be synchronized or neither should be synchronized. </p> <p>Example of violations: </p> <pre> class Person { String name Date birthday boolean deceased boolean parent int weight synchronized setName(String name) { this.name = name } // violation, get method should be synchronized String getName() { name } // violation, set method should be synchronized void setBirthday(Date birthday) { this.birthday = birthday } synchronized String getBirthday() { birthday } // violation, set method should be synchronized void setDeceased(boolean deceased) { this.deceased = deceased } synchronized boolean isDeceased() { deceased } synchronized void setParent(boolean parent) { this.parent = parent } // violation, get method should be synchronized boolean isParent() { parent } // violation get method should be synchronized @groovy.transform.Synchronized void setWeight(int value) { weight = value } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.StaticCalendarFieldRule</key> <severity>MINOR</severity> <name><![CDATA[Static Calendar Field]]></name> <internalKey><![CDATA[StaticCalendarField]]></internalKey> <description><![CDATA[<p><code>Calendar</code> objects should not be used as <code>static</code> fields. Calendars are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application. Under 1.4 problems seem to surface less often than under Java 5 where you will probably see random <code>ArrayIndexOutOfBoundsException</code> or <code>IndexOutOfBoundsException</code> in <code>sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate()</code>. You may also experience serialization problems. Using an instance field or a <code>ThreadLocal</code> is recommended. </p> <p>For more information on this see Sun Bug #6231579 and Sun Bug #6178997. </p> <p>Examples: </p> <pre> // Violations class MyClass { static Calendar calendar1 static java.util.Calendar calendar2 static final CAL1 = Calendar.getInstance() static final CAL2 = Calendar.getInstance(Locale.FRANCE) static def cal3 = Calendar.getInstance(timezone) static Object cal4 = Calendar.getInstance(timezone, locale) } // These usages are OK class MyCorrectClass { private final Calendar calendar1 static ThreadLocal<Calendar> calendar2 } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.StaticDateFormatFieldRule</key> <severity>MINOR</severity> <name><![CDATA[Static Date Format Field]]></name> <internalKey><![CDATA[StaticDateFormatField]]></internalKey> <description><![CDATA[<p><code>DateFormat</code> objects should not be used as <code>static</code> fields. DateFormats are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application. Under 1.4 problems seem to surface less often than under Java 5 where you will probably see random <code>ArrayIndexOutOfBoundsException</code> or <code>IndexOutOfBoundsException</code> in <code>sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate()</code>. You may also experience serialization problems. Using an instance field or a <code>ThreadLocal</code> is recommended. </p> <p>For more information on this see Sun Bug #6231579 and Sun Bug #6178997. </p> <p>Examples: </p> <pre> // Violations class MyClass { static DateFormat dateFormat1 static java.text.DateFormat dateFormat2 static final DATE1 = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE) static final def DATE2 = DateFormat.getDateInstance(DateFormat.LONG) static Object date3 = DateFormat.getDateInstance() static final DATETIME1 = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT, Locale.FRANCE) static final def DATETIME2 = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT) static final Object DATETIME3 = DateFormat.getDateTimeInstance() static final TIME1 = DateFormat.getTimeInstance(DateFormat.LONG, Locale.FRANCE) static final def TIME2 = DateFormat.getTimeInstance(DateFormat.LONG) static final Object TIME3 = DateFormat.getTimeInstance() } // These usages are OK class MyCorrectClass { private DateFormat calendar1 static ThreadLocal<DateFormat> calendar2 } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.StaticMatcherFieldRule</key> <severity>MINOR</severity> <name><![CDATA[Static Matcher Field]]></name> <internalKey><![CDATA[StaticMatcherField]]></internalKey> <description><![CDATA[<p>Matcher objects should not be used as static fields. Calendars are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application. </p> <p>Example of violations: </p> <pre> // two violations class MyClass { static Matcher matcher1 static java.util.regex.Matcher matcher2 } // these usages are OK class MyCorrectClass { private Matcher matcher1 static ThreadLocal<Matcher> matcher2 } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.SynchronizedOnBoxedPrimitiveRule</key> <severity>MINOR</severity> <name><![CDATA[Synchronized On Boxed Primitive]]></name> <internalKey><![CDATA[SynchronizedOnBoxedPrimitive]]></internalKey> <description><![CDATA[<p>The code synchronizes on a boxed primitive constant, such as an Integer. Since Integer objects can be cached and shared, this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness and possible deadlock. </p> <p>Example of violations: </p> <pre> class MyClass { Byte byte1 = 100 Short short1 = 1 Double double1 = 1 Integer integer1 = 1 Long long1 = 1 Float float1 = 1 Character char1 = 1 byte byte2 = getValue() short short2 = getValue() double double2 = getValue() int integer2 = getValue() long long2 = getValue() float float2 = getValue() char char2 = getValue() def byte3 = new Byte((byte)100) def short3 = new Short((short)1) def double3 = new Double((double)1) def integer3 = new Integer(1) def long3 = new Long(1) def float3 = new Float(1) def char3 = new Character((char)'1') def byte4 = 1 as byte def short4 = 1 as short def double4 = 1 as double def integer4 = 1 as int def long4 = 1 as long def float4 = 1 as float def char4 = 1 as char def byte5 = 1 as Byte def short5 = 1 as Short def double5 = 1 as Double def integer5 = 1 as Integer def long5 = 1 as Long def float5 = 1 as Float def char5 = 1 as Character def byte6 = (byte)1 def short6 = (short)1 def double6 = (double)1 def integer6 = (int)1 def long6 = (long)1 def float6 = (float)1 def char6 = (char)1 def method() { // all of these synchronization blocks produce violations synchronized(byte1) {} synchronized(short1) {} synchronized(double1) {} synchronized(integer1) {} synchronized(long1) {} synchronized(float1) {} synchronized(char1) {} synchronized(byte2) {} synchronized(short2) {} synchronized(double2) {} synchronized(integer2) {} synchronized(long2) {} synchronized(float2) {} synchronized(char2) {} synchronized(byte3) {} synchronized(short3) {} synchronized(double3) {} synchronized(integer3) {} synchronized(long3) {} synchronized(float3) {} synchronized(char3) {} synchronized(byte4) {} synchronized(short4) {} synchronized(double4) {} synchronized(integer4) {} synchronized(long4) {} synchronized(float4) {} synchronized(char4) {} synchronized(byte5) {} synchronized(short5) {} synchronized(double5) {} synchronized(integer5) {} synchronized(long5) {} synchronized(float5) {} synchronized(char5) {} synchronized(byte6) {} synchronized(short6) {} synchronized(double6) {} synchronized(integer6) {} synchronized(long6) {} synchronized(float6) {} synchronized(char6) {} } } </pre> <pre> class MyClass { final String lock = false def method() { // violation synchronized(lock) { } } } class MyClass { final String lock = false class MyInnerClass { def method() { // violation synchronized(lock) { } } } } class MyClass { // implicit typing final def lock = true def method() { // violation synchronized(lock) { } } } class MyClass { // implicit typing final def lock = new Object[0] // correct idiom def method() { return new Runnable() { final def lock = false // shadows parent from inner class public void run() { // violation synchronized(stringLock) { } } } } } class MyClass { // implicit typing final def lock = new Object[0] // correct idiom class MyInnerClass { final def lock = true // shadows parent from inner class def method() { // violation synchronized(stringLock) { } } } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.SynchronizedOnStringRule</key> <severity>MINOR</severity> <name><![CDATA[Synchronized On String]]></name> <internalKey><![CDATA[SynchronizedOnString]]></internalKey> <description><![CDATA[<p>Synchronization on a String field can lead to deadlock. Constant Strings are interned and shared across all other classes loaded by the JVM. Thus, this could is locking on something that other code might also be locking. This could result in very strange and hard to diagnose blocking and deadlock behavior. </p> <p>See <a href="http://www.javalobby.org/java/forums/t96352.html and http://jira.codehaus.org/browse/JETTY-352">JETTY-352</a>. </p> <p>Examples: </p> <pre> class MyClass { final String stringLock = "stringLock" def method() { // violation synchronized(stringLock) { } } } class MyClass { final String stringLock = "stringLock" class MyInnerClass { def method() { synchronized(stringLock) { } } } } class MyClass { // implicit typing final def stringLock = "stringLock" def method() { // violation synchronized(stringLock) { } } } class MyClass { // implicit typing final def lock = new Object[0] // correct idiom def method() { return new Runnable() { final def lock = "" // shadows parent from inner class public void run() { // violation synchronized(stringLock) { } } } } } class MyClass { // implicit typing final def lock = new Object[0] // correct idiom class MyInnerClass { final def lock = "" // shadows parent from inner class def method() { // violation synchronized(stringLock) { } } } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.SynchronizedReadObjectMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Synchronized Read Object Method]]></name> <internalKey><![CDATA[SynchronizedReadObjectMethod]]></internalKey> <description><![CDATA[<p>Catches Serializable classes that define a synchronized readObject method. By definition, an object created by deserialization is only reachable by one thread, and thus there is no need for readObject() to be synchronized. If the readObject() method itself is causing the object to become visible to another thread, that is an example of very dubious coding style. </p> <p>Examples: </p> <pre> class MyClass implements Serializable { private synchronized void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { // violation, no need to synchronized } } class MyClass implements Serializable { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { synchronized(lock) { // violation, no need to synchronized } } } // OK, class not Serializable class MyClass { private synchronized void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { } } // OK, class not Serializable class MyClass { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { synchronized(lock) { } } } class MyClass implements Serializable { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { // OK, this block is more than just a simple sync statement synchronized(lock) { } doSomething() } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.SynchronizedOnReentrantLockRule</key> <severity>MINOR</severity> <name><![CDATA[Synchronized On Reentrant Lock]]></name> <internalKey><![CDATA[SynchronizedOnReentrantLock]]></internalKey> <description><![CDATA[<p>Synchronizing on a ReentrantLock field is almost never the intended usage. A ReentrantLock should be obtained using the lock() method and released in a finally block using the unlock() method. </p> <p>This rule take from Alex Miller's <a href="http://www.slideshare.net/alexmiller/java-concurrency-gotchas-3666977">Java Concurrency in Practice</a> slides. </p> <p>Here is the proper usage of ReentrantLock: </p> <pre> import java.util.concurrent.locks.ReentrantLock; final lock = new ReentrantLock(); def method() { //Trying to enter the critical section lock.lock(); // will wait until this thread gets the lock try { // critical section } finally { //releasing the lock so that other threads can get notifies lock.unlock(); } } </pre> <pre> class MyClass { final ReentrantLock lock = new ReentrantLock() def method() { // violation synchronized(lock) { } } } class MyClass { final ReentrantLock lock = new ReentrantLock() class MyInnerClass { def method() { synchronized(lock) { } } } } class MyClass { // implicit typing final def lock = new ReentrantLock() def method() { // violation synchronized(lock) { } } } class MyClass { // implicit typing final def lock = new Object[0] // correct idiom def method() { return new Runnable() { final def lock = new ReentrantLock() // shadows parent from inner class public void run() { // violation synchronized(lock) { } } } } } class MyClass { // implicit typing final def lock = new Object[0] // correct idiom class MyInnerClass { final def lock = new ReentrantLock() // shadows parent from inner class def method() { // violation synchronized(lock) { } } } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.VolatileArrayFieldRule</key> <severity>MINOR</severity> <name><![CDATA[Volatile Array Field]]></name> <internalKey><![CDATA[VolatileArrayField]]></internalKey> <description><![CDATA[<p>Volatile array fields are unsafe because the contents of the array are not treated as volatile. Changing the entire array reference is visible to other threads, but changing an array element is not. </p> <p>This rule take from Alex Miller's <Java Concurrency in Practice> slides, available at <a>http://www.slideshare.net/alexmiller/java-concurrency-gotchas-3666977</a>. </p> <p>Example of violations: </p> <pre> class MyClass { private volatile Object[] field1 = value() volatile field2 = value as Object[] volatile field3 = (Object[])foo } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.concurrency.WaitOutsideOfWhileLoopRule</key> <severity>MINOR</severity> <name><![CDATA[Wait Outside Of While Loop]]></name> <internalKey><![CDATA[WaitOutsideOfWhileLoop]]></internalKey> <description><![CDATA[<p>Calls to <code>Object.wait()</code> must be within a <code>while</code> loop. This ensures that the awaited condition has not already been satisfied by another thread before the <code>wait()</code> is invoked. It also ensures that the proper thread was resumed and guards against incorrect notification. See [1] and [3]. </p> <p>As a more modern and flexible alternative, consider using the Java <concurrency utilities> instead of <code>wait()</code> and <code>notify()</code>. See discussion in <Effective Java> [2]. </p> <p>Example of violation: </p> <pre> class MyClass { private data void processData() synchronized(data) { if (!data.isReady()) { data.wait() } data.calculateStatistics() } } } </pre> <pre> class MyClass { private data void processData() synchronized(data) { while (!data.isReady()) { data.wait() } data.calculateStatistics() } } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.concurrency.StaticConnectionRule</key> <severity>MINOR</severity> <name><![CDATA[Static Connection]]></name> <internalKey><![CDATA[StaticConnection]]></internalKey> <description><![CDATA[<p>Creates violations when a <code>java.sql.Connection</code> object is used as a <code>static</code> field. Database connections stored in <code>static</code> fields will be shared between threads, which is unsafe and can lead to race conditions. </p> <p>A transactional resource object such as database connection can only be associated with one transaction at a time. For this reason, a connection should not be shared between threads and should not be stored in a static field. See Section 4.2.3 of the <J2EE Specification> for more details. </p> <p>References: </p> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.concurrency.StaticSimpleDateFormatFieldRule</key> <severity>MINOR</severity> <name><![CDATA[Static Simple Date Format Field]]></name> <internalKey><![CDATA[StaticSimpleDateFormatField]]></internalKey> <description><![CDATA[<p><code>SimpleDateFormat</code> objects should not be used as <code>static</code> fields. SimpleDateFormats are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application. Under 1.4 problems seem to surface less often than under Java 5 where you will probably see random <code>ArrayIndexOutOfBoundsException</code> or <code>IndexOutOfBoundsException</code> in <code>sun.util.calendar.BaseCalendar.getCalendarDateFromFixedDate()</code>. You may also experience serialization problems. Using an instance field or a <code>ThreadLocal</code> is recommended. </p> <p>For more information on this see Sun Bug #6231579 and Sun Bug #6178997. </p> <p>Examples: </p> <pre> // Violations class MyClass { static SimpleDateFormat dateFormat1 static java.text.SimpleDateFormat dateFormat2 static final DATE1 = new SimpleDateFormat() static final DATE2 = new SimpleDateFormat('MM/dd') static final DATE3 = new SimpleDateFormat('MM/dd', DateFormatSymbols.instance) static date4 = new SimpleDateFormat('MM/dd', Locale.FRANCE) static date5 = new java.text.SimpleDateFormat('MM/dd') } // These usages are OK class MyCorrectClass { private SimpleDateFormat calendar1 static ThreadLocal<SimpleDateFormat> calendar2 } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.concurrency.ThisReferenceEscapesConstructorRule</key> <severity>MINOR</severity> <name><![CDATA[This Reference Escapes Constructor]]></name> <internalKey><![CDATA[ThisReferenceEscapesConstructor]]></internalKey> <description><![CDATA[<p>Reports constructors passing the 'this' reference to other methods. This equals exposing a half-baked objects and can lead to race conditions during initialization. For reference, see <a href="http://www.slideshare.net/alexmiller/java-concurrency-gotchas-3666977/38">Java Concurrency in Practice</a> by Alex Miller and <a href="http://www.ibm.com/developerworks/java/library/j-jtp0618/index.html">Java theory and practice: Safe construction techniques</a> by Brian Goetz. </p> <p>Example of violations: </p> <pre> class EventListener { EventListener(EventPublisher publisher) { publisher.register(this) new WorkThread(publisher, this).start() new AnotherWorkThread(listener: this) } } </pre> ]]></description> <tag>multi-threading</tag> </rule> <!-- design rules --> <rule> <key>org.codenarc.rule.design.CloneableWithoutCloneRule</key> <severity>MINOR</severity> <name><![CDATA[Cloneable Without Clone]]></name> <internalKey><![CDATA[CloneableWithoutClone]]></internalKey> <description><![CDATA[<p>Checks for classes that implement the <code>java.lang.Cloneable</code> interface without implementing the <code>clone()</code> method. </p> <p>Here is an example of code that produces a violation: </p> <pre> class BadClass implements Cloneable { def someMethod() } </pre> ]]></description> <tag>design</tag> </rule> <rule> <key>org.codenarc.rule.design.ImplementationAsTypeRule</key> <severity>MINOR</severity> <name><![CDATA[Implementation As Type]]></name> <internalKey><![CDATA[ImplementationAsType]]></internalKey> <description><![CDATA[<p>Checks for use of the following concrete classes when specifying the type of a method parameter, closure parameter, constructor parameter, method return type or field type. The corresponding interfaces should be used to specify the type instead. </p> ]]></description> <tag>design</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.design.BooleanMethodReturnsNullRule</key> <severity>MINOR</severity> <name><![CDATA[Boolean Method Returns Null]]></name> <internalKey><![CDATA[BooleanMethodReturnsNull]]></internalKey> <description><![CDATA[<p>Checks for a method with <code>Boolean</code> return type that returns an explicit <code>null</code>. A method that returns either <code>Boolean.TRUE</code>, <code>Boolean.FALSE</code> or <code>null</code> is an accident waiting to happen. This method can be invoked as though it returned a value of type <code>boolean</code>, and the compiler will insert automatic <unboxing> of the <code>Boolean</code> value. If a <code>null</code> value is returned, this will result in a <code>NullPointerException</code>. </p> ]]></description> <tag>design</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.design.ReturnsNullInsteadOfEmptyArrayRule</key> <severity>MINOR</severity> <name><![CDATA[Returns Null Instead Of Empty Array]]></name> <internalKey><![CDATA[ReturnsNullInsteadOfEmptyArray]]></internalKey> <description><![CDATA[<p>If you have a method or closure that returns an array, then when there are no results return a zero-length (empty) array rather than <code>null</code>. It is often a better design to return a zero-length array rather than a <code>null</code> reference to indicate that there are no results (i.e., an <empty> list of results). This way, no explicit check for <code>null</code> is needed by clients of the method. </p> ]]></description> <tag>design</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.design.ReturnsNullInsteadOfEmptyCollectionRule</key> <severity>MINOR</severity> <name><![CDATA[Returns Null Instead Of Empty Collection]]></name> <internalKey><![CDATA[ReturnsNullInsteadOfEmptyCollection]]></internalKey> <description><![CDATA[<p>If you have a method or closure that returns a collection, then when there are no results return a zero-length (empty) collection rather than <code>null</code>. It is often a better design to return a zero-length collection rather than a <code>null</code> reference to indicate that there are no results (i.e., an <empty> list of results). This way, no explicit check for <code>null</code> is needed by clients of the method. </p> ]]></description> <tag>design</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.design.CompareToWithoutComparableRule</key> <severity>MINOR</severity> <name><![CDATA[Compare To Without Comparable]]></name> <internalKey><![CDATA[CompareToWithoutComparable]]></internalKey> <description><![CDATA[<p>If you implement a compareTo method then you should also implement the <code>Comparable</code> interface. If you don't then you could possibly get an exception if the Groovy == operator is invoked on your object. This is an issue fixed in Groovy 1.8 but present in previous versions. </p> <p>Here is an example of code that produces a violation: </p> <pre> class BadClass { int compareTo(Object o) { ... } } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.design.SimpleDateFormatMissingLocaleRule</key> <severity>MINOR</severity> <name><![CDATA[Simple Date Format Missing Locale]]></name> <internalKey><![CDATA[SimpleDateFormatMissingLocale]]></internalKey> <description><![CDATA[<p>Be sure to specify a <code>Locale</code> when creating a new instance of <code>SimpleDateFormat</code>; the class is locale-sensitive. If you instantiate <code>SimpleDateFormat</code> without a <code>Locale</code> parameter, it will format the date and time according to the default <code>Locale</code>. Both the pattern and the <code>Locale</code> determine the format. For the same pattern, <code>SimpleDateFormat</code> may format a date and time differently if the Locale varies. </p> <pre> // violation, missing locale new SimpleDateFormat('pattern') // OK, includes locale new SimpleDateFormat('pattern', Locale.US) // OK, includes a variable that perhaps is a locale new SimpleDateFormat('pattern', locale) </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.design.AbstractClassWithoutAbstractMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Abstract Class Without Abstract Method]]></name> <internalKey><![CDATA[AbstractClassWithoutAbstractMethod]]></internalKey> <description><![CDATA[<p>The abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods. If the class is intended to be used as a base class only (not to be instantiated directly) a protected constructor can be provided prevent direct instantiation. </p> <p>Example: </p> <pre> public abstract class MyBaseClass { void method1() { } void method2() { } // consider using abstract methods or removing // the abstract modifier and adding protected constructors } </pre> <pre> abstract class MyClass extends AbstractParent { // OK because parent is named Abstract.* } abstract class MyClass extends BaseParent{ // OK because parent is named Base.* } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.design.CloseWithoutCloseableRule</key> <severity>MINOR</severity> <name><![CDATA[Close Without Closeable]]></name> <internalKey><![CDATA[CloseWithoutCloseable]]></internalKey> <description><![CDATA[<p>If a class defines a "void close()" then that class should implement java.io.Closeable. </p> ]]></description> <tag>design</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.design.ConstantsOnlyInterfaceRule</key> <severity>MINOR</severity> <name><![CDATA[Constants Only Interface]]></name> <internalKey><![CDATA[ConstantsOnlyInterface]]></internalKey> <description><![CDATA[<p>An interface should be used only to model a behaviour of a class: using an interface as a container of constants is a poor usage pattern. Example: </p> <pre> public interface ConstantsInterface { public static final int CONSTANT_1 = 0 public static final String CONSTANT_2 = "1" } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.design.EmptyMethodInAbstractClassRule</key> <severity>MINOR</severity> <name><![CDATA[Empty Method In Abstract Class]]></name> <internalKey><![CDATA[EmptyMethodInAbstractClass]]></internalKey> <description><![CDATA[<p>An empty method in an abstract class should be abstract instead, as developer may rely on this empty implementation rather than code the appropriate one. </p> <pre> abstract class MyClass { def couldBeAbstract_1() { return null // Should be abstract method } void couldBeAbstract_2() { // Should be abstract method } } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.design.FinalClassWithProtectedMemberRule</key> <severity>MINOR</severity> <name><![CDATA[Final Class With Protected Member]]></name> <internalKey><![CDATA[FinalClassWithProtectedMember]]></internalKey> <description><![CDATA[<p>This rule finds classes marked final that contain <code>protected</code> members. If a class is <code>final</code> then it may not be subclassed, and there is therefore no point in having a member with <code>protected</code> visibility. Either the class should not be <code>final</code> or the member should be private or protected. </p> ]]></description> <tag>design</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.design.PublicInstanceFieldRule</key> <severity>MINOR</severity> <name><![CDATA[Public Instance Field]]></name> <internalKey><![CDATA[PublicInstanceField]]></internalKey> <description><![CDATA[<p>Using public fields is considered to be a bad design. Use properties instead. </p> <p>Example of violations: </p> <pre> class Person { public String name } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.design.StatelessSingletonRule</key> <severity>MINOR</severity> <name><![CDATA[Stateless Singleton]]></name> <internalKey><![CDATA[StatelessSingleton]]></internalKey> <description><![CDATA[<p>There is no point in creating a stateless Singleton because there is nothing within the class that needs guarding and no side effects to calling the constructor. Just create new instances of the object or write a Utility class with static methods. In the long term, Singletons can cause strong coupling and hard to change systems. </p> <p>If the class has any fields at all, other than a self reference, then it is not considered stateless. A self reference is a field of the same type as the enclosing type, or a field named instance or _instance. The field name self reference is a property named instanceRegex that defaults to the value 'instance|_instance' </p> <p>Example of violations: </p> <pre> @groovy.lang.Singleton class Service { // violation: the class has no fields but is marked Singleton void processItem(item){ } } class Service { // violation: the class has no fields other than 'instance' but is marked Singleton static instance void processItem(item){ } } class Service { // violation static Service service void processItem(item){ } } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.design.AbstractClassWithPublicConstructorRule</key> <severity>MINOR</severity> <name><![CDATA[Abstract Class With Public Constructor]]></name> <internalKey><![CDATA[AbstractClassWithPublicConstructor]]></internalKey> <description><![CDATA[<p>Checks for <code>abstract</code> classes that define a <code>public</code> constructor, which is useless and confusing. </p> <p>The following code produces a violation: </p> <pre> abstract class MyClass { MyClass() { } } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.design.BuilderMethodWithSideEffectsRule</key> <severity>MINOR</severity> <name><![CDATA[Builder Method With Side Effects]]></name> <internalKey><![CDATA[BuilderMethodWithSideEffects]]></internalKey> <description><![CDATA[<p>A builder method is defined as one that creates objects. As such, they should never be of void return type. If a method is named build, create, or make, then it should always return a value. </p> <p>This rule has one property: <code>methodNameRegex</code>. The default value is (make.*|create.*|build.*). Update this property if you have some other naming convention for your builder methods. </p> <p>Example of violations: </p> <pre> class MyClass { void make() { /* ... */ } void makeSomething() { /* ... */ } void create() { /* ... */ } void createSomething() { /* ... */ } void build() { /* ... */ } void buildSomething() { /* ... */ } } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.17 --> <rule> <key>org.codenarc.rule.design.PrivateFieldCouldBeFinalRule.fixed</key> <severity>MAJOR</severity> <name><![CDATA[Private Field Could Be Final]]></name> <internalKey><![CDATA[PrivateFieldCouldBeFinal]]></internalKey> <description><![CDATA[<p>This rule finds <code>private</code> fields that are only set within a <constructor> or <field initializer>. Such fields can safely be made <code>final</code>. </p> ]]></description> <tag>design</tag> <param> <key>ignoreFieldNames</key> <description><![CDATA[Specifies one or more (comma-separated) field names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> <param> <key>ignoreJpaEntities</key> <description><![CDATA[Specifies whether fields defined inside classes annotated with @Entity or @MappedSuperclass JPA annotations should be ignored (i.e., that should not cause a rule violation). ]]></description> <defaultValue>false</defaultValue> </param> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.design.CloneWithoutCloneableRule</key> <severity>MINOR</severity> <name><![CDATA[Clone Without Cloneable]]></name> <internalKey><![CDATA[CloneWithoutCloneable]]></internalKey> <description><![CDATA[<p>The method clone() should only be declared if the class implements the Cloneable interface. </p> <p>NOTE: This is a <a href="http://codenarc.sourceforge.net/codenarc-enhanced-classpath-rules.html">CodeNarc Enhanced Classpath Rule</a>. It requires <code>CodeNarc</code> to have the application classes being analyzed, as well as any referenced classes, on the classpath. </p> <p>Example of violations: </p> <pre> class ValueClass { ValueClass clone() { } } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.20 --> <rule> <key>org.codenarc.rule.design.LocaleSetDefaultRule</key> <severity>MINOR</severity> <name><![CDATA[Locale Set Default]]></name> <internalKey><![CDATA[LocaleSetDefault]]></internalKey> <description><![CDATA[<p>Checks for calls to <code>Locale.setDefault()</code>, or <code>Locale.default = Xxx</code>, which sets the Locale across the entire JVM. That can impact other applications on the same web server, for instance. </p> <p>From the java.util.Locale javadoc for <code>setDefault</code>: should only be used if the caller is prepared to reinitialize locale-sensitive code running within the same Java Virtual Machine.> </p> <p>Example of violations: </p> <pre> Locale.setDefault(Locale.UK) // violation java.util.Locale.setDefault(Locale.FRANCE) // violation Locale.setDefault(Locale.Category.DISPLAY, Locale.JAPAN) // violation Locale.default = Locale.UK // violation </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.design.ToStringReturnsNullRule</key> <severity>MINOR</severity> <name><![CDATA[To String Returns Null]]></name> <internalKey><![CDATA[ToStringReturnsNull]]></internalKey> <description><![CDATA[<p>Checks for <code>toString()</code> methods that return <code>null</code>. This is unconventional and could cause unexpected <code>NullPointerExceptions</code> from normal or implicit use of <code>toString()</code>. </p> <p>Example of violations: </p> <pre> class MyClass { String toString() { if (foo()) { return 'MyClass' } else { return null // violation } } } class MyClass { String toString() { calculateStuff() null // violation } } class MyClass { String toString() { // violation - implicit return of null } } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.22 --> <rule> <key>org.codenarc.rule.design.InstanceofRule</key> <severity>MINOR</severity> <name><![CDATA[Instanceof]]></name> <internalKey><![CDATA[Instanceof]]></internalKey> <description><![CDATA[<p>Checks for use of the <code>instanceof</code> operator. Prefer using <polymorphism> instead. </p> <p>Use the <code>ignoreTypeNames</code> property to configure ignored type names (the class name specified as the right-hand expression of the <code>instanceof</code>). It defaults to ignoring <code>instanceof</code> checks against exception classes. </p> <p>Here are a couple references that discuss the problems with using <code>instanceof</code> and the preference for using <polymorphism> instead: </p> <p>* <a href="http://www.javapractices.com/topic/TopicAction.do?Id=31">Beware of instanceof operator</a> </p> <p>* <a href="http://stackoverflow.com/questions/4192837/how-does-one-use-polymorphism-instead-of-instanceof-and-why">How does one use polymorphism instead of instanceof? (And why?)</a> </p> <p>By default, the rule does not analyze test files. This rule sets the default value of the <doNotApplyToFilesMatching> property to ignore file names ending in 'Test.groovy', 'Tests.groovy' or 'TestCase.groovy'. </p> <p>Example of violations: </p> <pre> class MyClass { boolean isRunnable = this instanceof Runnable // violation } </pre> ]]></description> <tag>design</tag> <param> <key>ignoreTypeNames</key> <description><![CDATA[Specifies one or more (comma-separated) class names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> <defaultValue>*Exceptions</defaultValue> </param> </rule> <!-- since 0.23 --> <rule> <key>org.codenarc.rule.design.NestedForLoopRule</key> <severity>MAJOR</severity> <name><![CDATA[Nested For Loop]]></name> <internalKey><![CDATA[NestedForLoop]]></internalKey> <description><![CDATA[<p>Reports classes with nested for loops. </p> <p>Example of violations: </p> <pre> for (int i = 0; i < 100; ++i) { for (int j = 0; j < 100; ++j) { // violation println i + j } } for (int i = 0; i < 100; ++i) { for (int j = 0; j < 100; ++j) { // violation println i + j } for (int j = 0; j < 100; ++j) { // violation println i + j } } for (int i = 0; i < 100; ++i) { for (int j = 0; j < 100; ++j) { // violation for (int k = 0; k < 100; ++k) { // violation println i + j + k } } } </pre> ]]></description> <tag>design</tag> </rule> <!-- since 0.24 --> <rule> <key>org.codenarc.rule.design.AssignmentToStaticFieldFromInstanceMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Assignment To Static Field From Instance Method]]></name> <internalKey><![CDATA[AssignmentToStaticFieldFromInstanceMethod]]></internalKey> <description><![CDATA[<p>Checks for assignment to a static field from an instance method. </p> <p>Influenced by the <code>AssignmentToNonFinalStatic</code> rule from <code>PMD</code>, and the <code>ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD</code> rule from <code>FindBugs</code>. </p> <p>Example of violations: </p> <pre> class MyClass { private static field1 protected static String field2 = 'abc' public static int field3 = 123 static String property1 = 'abc' private static final NAME = 'joe' private void doStuff() { field1 = new Object() // violation field2 = 'xxx' // violation field3 = 999 // violation property1 = 'xxx' // violation final NAME = 'martin' // no violation; local var hides static field } } </pre> ]]></description> <tag>design</tag> </rule> <!-- dry rules --> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.dry.DuplicateNumberLiteralRule</key> <severity>MINOR</severity> <name><![CDATA[Duplicate Number Literal]]></name> <internalKey><![CDATA[DuplicateNumberLiteral]]></internalKey> <description><![CDATA[<p> This rule checks for duplicate number literals within the current class. </p> <p>Code containing duplicate <Number> literals can usually be improved by declaring the <Number> as a constant field. </p> <p>By default, the rule does not analyze test files. This rule sets the default value of the <doNotApplyToFilesMatching> property to ignore file names ending in 'Test.groovy', 'Tests.groovy' or 'TestCase.groovy'. </p> ]]></description> <tag>bug</tag> <param> <key>ignoreNumbers</key> <description><![CDATA[The optional comma-separated list of numbers that should be ignored (i.e., not cause a violation). ]]></description> <defaultValue>0,1</defaultValue> </param> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.dry.DuplicateStringLiteralRule</key> <severity>MINOR</severity> <name><![CDATA[Duplicate String Literal]]></name> <internalKey><![CDATA[DuplicateStringLiteral]]></internalKey> <description><![CDATA[<p> This rule checks for duplicate String literals within the current class. </p> <p>Code containing duplicate <String> literals can usually be improved by declaring the <String> as a constant field. </p> <p>By default, the rule does not analyze test files. This rule sets the default value of the <doNotApplyToFilesMatching> property to ignore file names ending in 'Test.groovy', 'Tests.groovy' or 'TestCase.groovy'. </p> ]]></description> <tag>bug</tag> <param> <key>ignoreStrings</key> <description><![CDATA[The optional comma-separated list of Strings that should be ignored (i.e., not cause a violation). ]]></description> <defaultValue>'' (empty string)</defaultValue> </param> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.dry.DuplicateMapLiteralRule</key> <severity>MAJOR</severity> <name><![CDATA[Duplicate Map Literal]]></name> <internalKey><![CDATA[DuplicateMapLiteral]]></internalKey> <description><![CDATA[<p> This rule checks for duplicate <Map> literals within the current class. This rule only checks for <Map>s where the keys and values are all constants or literals. </p> <p>Code containing duplicate <Map> literals can usually be improved by declaring the <Map> as a constant field. </p> <p>By default, the rule does not analyze test files. This rule sets the default value of the <doNotApplyToFilesMatching> property to ignore file names ending in 'Test.groovy', 'Tests.groovy' or 'TestCase.groovy'. </p> <p>Examples of violations: </p> <pre> def var1 = [a:1, b:null, c:Boolean.FALSE, d:'x', e:true] def var2 = [a:1, b:null, c:Boolean.FALSE, d:'x', e:true] // violation def var1 = [a:1, b:[x:3,y:4]] def var2 = [a:1, b:[x:3,y:4]] // violation def var1 = [a:1, b:[3,4]] def var2 = [a:1, b:[3,4]] // violation def var1 = [null:1, 'b':2, (Boolean.FALSE):3, (4):4, (true):5] def var2 = [null:1, 'b':2, (Boolean.FALSE):3, (4):4, (true):5] // violation </pre> <pre> def name def var1 = [(name):1, b:1, c:1] def var2 = [(name):1, b:1, c:1] // not a violation; name is a variable def var1 = [a:1, b:['x', name]] def var2 = [a:1, b:['x', name]] // not a violation; name is a variable def var1 = [a:7+5] def var2 = [a:7+5] // not a violation; contains a non-constant/literal expression </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.dry.DuplicateListLiteralRule</key> <severity>MAJOR</severity> <name><![CDATA[Duplicate List Literal]]></name> <internalKey><![CDATA[DuplicateListLiteral]]></internalKey> <description><![CDATA[<p> This rule checks for duplicate <List> literals within the current class. This rule only checks for <List>s where values are all constants or literals. </p> <p>Code containing duplicate <List> literals can usually be improved by declaring the <List> as a constant field. </p> <p>By default, the rule does not analyze test files. This rule sets the default value of the <doNotApplyToFilesMatching> property to ignore file names ending in 'Test.groovy', 'Tests.groovy' or 'TestCase.groovy'. </p> <p>Examples of violations: </p> <pre> def var1 = [1, null, Boolean.FALSE, 'x', true] def var2 = [1, null, Boolean.FALSE, 'x', true] // violation def var1 = [1, [3, 4]] def var2 = [1, [3,4]] // violation def var1 = [123, [3, 4, [x:99], 5]] def var2 = [99, [3, 4, [x:99], 5]] // violation [3, 4, [x:99], 5] </pre> <pre> def name def var1 = [name, 'b', 'c'] def var2 = [name, 'b', 'c'] // not a violation; name is a variable def var1 = [1, 7+5] def var2 = [1, 7+5] // not a violation; contains a non-constant/literal expression </pre> ]]></description> <tag>bug</tag> </rule> <!-- exceptions rules --> <rule> <key>org.codenarc.rule.exceptions.CatchErrorRule</key> <severity>MINOR</severity> <name><![CDATA[Catch Error]]></name> <internalKey><![CDATA[CatchError]]></internalKey> <description><![CDATA[<p>Checks for catching a <code>Error</code>. In most cases that is much too broad, and is also dangerous because it can catch exceptions such as <code>ThreadDeath</code> and <code>OutOfMemoryError</code>. </p> ]]></description> <tag>error-handling</tag> </rule> <rule> <key>org.codenarc.rule.exceptions.CatchExceptionRule</key> <severity>MINOR</severity> <name><![CDATA[Catch Exception]]></name> <internalKey><![CDATA[CatchException]]></internalKey> <description><![CDATA[<p>Checks for catching a <code>Exception</code>. In most cases that is too broad or general. It should usually be restricted to framework or infrastructure code, rather than application code. </p> ]]></description> <tag>error-handling</tag> </rule> <rule> <key>org.codenarc.rule.exceptions.CatchNullPointerExceptionRule</key> <severity>MINOR</severity> <name><![CDATA[Catch Null Pointer Exception]]></name> <internalKey><![CDATA[CatchNullPointerException]]></internalKey> <description><![CDATA[<p>Checks for catching a <code>NullPointerException</code>. Catching <code>NullPointerException</code> is never appropriate. It should be avoided in the first place with proper null checking, and it can mask underlying errors. </p> ]]></description> <tag>error-handling</tag> </rule> <rule> <key>org.codenarc.rule.exceptions.CatchRuntimeExceptionRule</key> <severity>MINOR</severity> <name><![CDATA[Catch Runtime Exception]]></name> <internalKey><![CDATA[CatchRuntimeException]]></internalKey> <description><![CDATA[<p>Checks for catching a <code>RuntimeException</code>. In most cases that is too broad or general. It should usually be restricted to framework or infrastructure code, rather than application code. </p> ]]></description> <tag>error-handling</tag> </rule> <rule> <key>org.codenarc.rule.exceptions.CatchThrowableRule</key> <severity>MINOR</severity> <name><![CDATA[Catch Throwable]]></name> <internalKey><![CDATA[CatchThrowable]]></internalKey> <description><![CDATA[<p>Checks for catching a <code>Throwable</code>. In most cases that is much too broad, and is also dangerous because it can catch exceptions such as <code>ThreadDeath</code> and <code>OutOfMemoryError</code>. </p> ]]></description> <tag>error-handling</tag> </rule> <rule> <key>org.codenarc.rule.exceptions.ThrowErrorRule</key> <severity>MINOR</severity> <name><![CDATA[Throw Error]]></name> <internalKey><![CDATA[ThrowError]]></internalKey> <description><![CDATA[<p>Checks for throwing an instance of <code>java.lang.Error</code>. This is not appropriate within normal application code. Throw an instance of a more specific exception subclass instead. </p> ]]></description> <tag>error-handling</tag> </rule> <rule> <key>org.codenarc.rule.exceptions.ThrowExceptionRule</key> <severity>MINOR</severity> <name><![CDATA[Throw Exception]]></name> <internalKey><![CDATA[ThrowException]]></internalKey> <description><![CDATA[<p>Checks for throwing an instance of <code>java.lang.Exception</code>. Throw an instance of a more specific exception subclass instead. </p> ]]></description> <tag>error-handling</tag> </rule> <rule> <key>org.codenarc.rule.exceptions.ThrowNullPointerExceptionRule</key> <severity>MINOR</severity> <name><![CDATA[Throw Null Pointer Exception]]></name> <internalKey><![CDATA[ThrowNullPointerException]]></internalKey> <description><![CDATA[<p>Checks for throwing an instance of <code>java.lang.NullPointerException</code>. Applications should never throw a <code>NullPointerException</code>. </p> ]]></description> <tag>error-handling</tag> </rule> <rule> <key>org.codenarc.rule.exceptions.ThrowRuntimeExceptionRule</key> <severity>MINOR</severity> <name><![CDATA[Throw Runtime Exception]]></name> <internalKey><![CDATA[ThrowRuntimeException]]></internalKey> <description><![CDATA[<p>Checks for throwing an instance of <code>java.lang.RuntimeException</code>. Throw an instance of a more specific exception subclass instead. </p> ]]></description> <tag>error-handling</tag> </rule> <rule> <key>org.codenarc.rule.exceptions.ThrowThrowableRule</key> <severity>MINOR</severity> <name><![CDATA[Throw Throwable]]></name> <internalKey><![CDATA[ThrowThrowable]]></internalKey> <description><![CDATA[<p>Checks for throwing an instance of <code>java.lang.Throwable</code>. Throw an instance of a more specific exception subclass instead. </p> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.exceptions.CatchIllegalMonitorStateExceptionRule</key> <severity>MINOR</severity> <name><![CDATA[Catch Illegal Monitor State Exception]]></name> <internalKey><![CDATA[CatchIllegalMonitorStateException]]></internalKey> <description><![CDATA[<p>Dubious catching of IllegalMonitorStateException. IllegalMonitorStateException is generally only thrown in case of a design flaw in your code (calling wait or notify on an object you do not hold a lock on). </p> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.exceptions.ConfusingClassNamedExceptionRule</key> <severity>MINOR</severity> <name><![CDATA[Confusing Class Named Exception]]></name> <internalKey><![CDATA[ConfusingClassNamedException]]></internalKey> <description><![CDATA[<p>This class is not derived from another exception, but ends with 'Exception'. This will be confusing to users of this class. </p> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.exceptions.ReturnNullFromCatchBlockRule</key> <severity>MINOR</severity> <name><![CDATA[Return Null From Catch Block]]></name> <internalKey><![CDATA[ReturnNullFromCatchBlock]]></internalKey> <description><![CDATA[<p>Returning null from a catch block often masks errors and requires the client to handle error codes. In some coding styles this is discouraged. This rule ignores methods with <code>void</code> return type. </p> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.exceptions.CatchArrayIndexOutOfBoundsExceptionRule</key> <severity>MINOR</severity> <name><![CDATA[Catch Array Index Out Of Bounds Exception]]></name> <internalKey><![CDATA[CatchArrayIndexOutOfBoundsException]]></internalKey> <description><![CDATA[<p>Checks for catching a <code>ArrayIndexOutOfBoundsException</code>. Catching <code>ArrayIndexOutOfBoundsException</code> should be avoided in the first place by checking the array size before accessing an array element. Catching the exception may mask underlying errors. </p> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.exceptions.CatchIndexOutOfBoundsExceptionRule</key> <severity>MINOR</severity> <name><![CDATA[Catch Index Out Of Bounds Exception]]></name> <internalKey><![CDATA[CatchIndexOutOfBoundsException]]></internalKey> <description><![CDATA[<p>Checks for catching a <code>IndexOutOfBoundsException</code>. Catching <code>IndexOutOfBoundsException</code> should be avoided in the first place by checking for a valid index before accessing an indexed element. Catching the exception may mask underlying errors. </p> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.exceptions.MissingNewInThrowStatementRule</key> <severity>MINOR</severity> <name><![CDATA[Missing New In Throw Statement]]></name> <internalKey><![CDATA[MissingNewInThrowStatement]]></internalKey> <description><![CDATA[<p>A common Groovy mistake when throwing exceptions is to forget the new keyword. For instance, <code>throw RuntimeException()</code> instead of <code>throw new RuntimeException()</code>. If the error path is not unit tested then the production system will throw a Method Missing exception and hide the root cause. This rule finds constructs like <code>throw RuntimeException()</code> that look like a new keyword was meant to be used but forgotten. </p> <p>The following code will all cause violations: </p> <pre> throw RuntimeException() // ends in Exceptions, first letter Capitalized throw RuntimeFailure() // ends in Failure, first letter Capitalized throw RuntimeFault(foo) // ends in Fault, first letter Capitalized </pre> <pre> throw new RuntimeException() throw runtimeFailure() // first letter lowercase, assumed to be method call </pre> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.exceptions.ExceptionExtendsErrorRule</key> <severity>MINOR</severity> <name><![CDATA[Exception Extends Error]]></name> <internalKey><![CDATA[ExceptionExtendsError]]></internalKey> <description><![CDATA[<p>Errors are system exceptions. Do not extend them. </p> <p>Examples: </p> <pre> class MyError extends Error { } // violation class MyError extends java.lang.Error { } // violation class MyException extends Exception { } // OK </pre> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.exceptions.SwallowThreadDeathRule</key> <severity>MINOR</severity> <name><![CDATA[Swallow Thread Death]]></name> <internalKey><![CDATA[SwallowThreadDeath]]></internalKey> <description><![CDATA[<p>Detects code that catches java.lang.ThreadDeath without re-throwing it.</p> <p>Example of violations: </p> <pre> try { def a = 0 } catch (ThreadDeath td) { td.printStackTrace() } </pre> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.exceptions.ExceptionNotThrownRule</key> <severity>MINOR</severity> <name><![CDATA[Exception Not Thrown]]></name> <internalKey><![CDATA[ExceptionNotThrown]]></internalKey> <description><![CDATA[<p> Checks for an exception constructor call without a <code>throw</code> as the last statement within a catch block. This rule treats any constructor call for a class named <xxx><code>Exception</code> as an exception constructor call. </p> <p>Example of violations: </p> <pre> void execute() { try { } catch(Exception e) { new Exception(e) } // violation } try { doStuff() } catch(DaoException e) { log.warning("Ooops", e) new ServiceException(e) // violation } catch(Exception e) { new SystemException(e) // violation } try { doStuff() } catch(Exception e) { throw new DaoException(e) } // ok </pre> ]]></description> <tag>error-handling</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.exceptions.ExceptionExtendsThrowableRule</key> <severity>MINOR</severity> <name><![CDATA[Exception Extends Throwable]]></name> <internalKey><![CDATA[ExceptionExtendsThrowable]]></internalKey> <description><![CDATA[<p>Checks for classes that extend <code>Throwable</code>. Custom exception classes should subclass <code>Exception</code> or one of its descendants. </p> <p>Example of violations: </p> <pre> class MyException extends Throwable { } // violation </pre> ]]></description> <tag>error-handling</tag> </rule> <!-- generic rules --> <rule> <key>org.codenarc.rule.generic.IllegalRegexRule.fixed</key> <severity>MAJOR</severity> <name><![CDATA[Illegal Regex]]></name> <internalKey><![CDATA[IllegalRegex]]></internalKey> <description><![CDATA[<p>Checks for a specified illegal regular expression within the source code. </p> <p>A RuleSet can contain any number of instances of this rule, but each should be configured with a unique rule <name> and <regex>, and (optionally) customized <violationMessage> and <priority>. </p> <p><code>NOTE:</code> This rule applies to the text contents of an entire <file> rather than a specific <class>, so it does not support the <applyToClassNames> and <doNotApplyToClassNames> configuration properties. </p> ]]></description> <tag>bug</tag> <param> <key>regex</key> <description><![CDATA[The regular expression to check for. If null or empty then do nothing. ]]></description> </param> </rule> <rule> <key>org.codenarc.rule.generic.RequiredRegexRule.fixed</key> <severity>MAJOR</severity> <name><![CDATA[Required Regex]]></name> <internalKey><![CDATA[RequiredRegex]]></internalKey> <description><![CDATA[<p>Checks for a specified regular expression that must exist within the source code. </p> <p>A RuleSet can contain any number of instances of this rule, but each should be configured with a unique rule <name> and <regex>, and (optionally) customized <violationMessage> and <priority>. </p> <p><code>NOTE:</code> This rule applies to the text contents of an entire <file> rather than a specific <class>, so it does not support the <applyToClassNames> and <doNotApplyToClassNames> configuration properties. </p> ]]></description> <tag>bug</tag> <param> <key>regex</key> <description><![CDATA[The regular expression to check for. If null or empty then do nothing. ]]></description> </param> </rule> <rule> <key>org.codenarc.rule.generic.RequiredStringRule.fixed</key> <severity>MAJOR</severity> <name><![CDATA[Required String]]></name> <internalKey><![CDATA[RequiredString]]></internalKey> <description><![CDATA[<p>Checks for a specified text string that must exist within the source code. </p> <p>A RuleSet can contain any number of instances of this rule, but each should be configured with a unique rule <name> and <string>, and (optionally) customized <violationMessage> and <priority>. </p> <p><code>NOTE:</code> This rule applies to the text contents of an entire <file> rather than a specific <class>, so it does not support the <applyToClassNames> and <doNotApplyToClassNames> configuration properties. </p> ]]></description> <tag>bug</tag> <param> <key>string</key> <description><![CDATA[The String to check for. If null or empty then do nothing. ]]></description> </param> </rule> <rule> <key>org.codenarc.rule.generic.StatelessClassRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Stateless Class]]></name> <internalKey><![CDATA[StatelessClass]]></internalKey> <description><![CDATA[<p>Checks for non-<code>final</code> fields on a class. The intent of this rule is to check a configured set of classes that should remain "stateless" and reentrant. One example might be Grails service classes which are singletons, by default, and so they should be reentrant. </p> <p>This rule ignores <code>final</code> fields (either instance or static). Fields that are <code>static</code> and non-<code>final</code>, however, do cause a violation. </p> <p>This rule also ignores all classes annotated with the <code>@Immutable</code> transformation. See <a href="http://groovy.codehaus.org/Immutable+transformation">http://groovy.codehaus.org/Immutable+transformation</a>. </p> <p>This rule also ignores all fields annotated with the <code>@Inject</code> annotation. </p> <p>You can configure this rule to ignore certain fields either by name or by type. This can be useful to ignore fields that hold references to (static) dependencies (such as DAOs or Service objects) or static configuration. </p> <p>Note that you can use the standard rule properties, such as <code>applyToClassNames</code>, <code>doNotApplyToFileNames</code> and <code>applyToFilesMatching</code> to only apply this rule to a subset of all classes/files. These rule properties are described in <a href="http://codenarc.sourceforge.net/codenarc-configuring-rules.html#Standard_Properties_for_Configuring_Rules"> Standard Properties for Configuring Rules</a>. </p> [[1]] The <code>ignoreFieldTypes</code> property matches the field type name as indicated in the field declaration, only including a full package specification IF it is included in the source code. For example, the field declaration <code>BigDecimal value</code> matches an <code>ignoreFieldTypes</code> value of <code>BigDecimal</code>, but not <code>java.lang.BigDecimal</code>. </p> <p>[[2]] There is one exception for the <code>ignoreFieldTypes</code> property: if the field is declared with a modifier/type of <code>def</code>, then the type resolves to <code>java.lang.Object</code>. </p> <p>[[3]] At least one of the (standard) <code>applyToClassNames</code>, <code>applyToFileNames</code> or <code>applyToFilesMatching</code> properties must be set (i.e., not null or empty) or else this rule does nothing. In other words, you must configure this rule to apply to a specific set of classes or files. </p> <p>[[4]] This rule will not catch violations of true <statelessness>/<reentrancy> if you define a <code>final</code> field whose value is itself mutable, e.g. a <code>final HashMap</code>. </p> ]]></description> <tag>bug</tag> <param> <key>addToIgnoreFieldNames</key> <description><![CDATA[Specifies one or more (comma-separated) field names to be added to the ignoreFieldNames property value. This is a special write-only property, and each call to setAddIgnoreFieldNames() adds to (rather than overwrites) the list of field names to be ignored. ]]></description> </param> <param> <key>ignoreFieldNames</key> <description><![CDATA[Specifies one or more (comma-separated) field names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> <param> <key>ignoreFieldTypes</key> <description><![CDATA[Specifies one or more (comma-separated) field types that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.generic.IllegalPackageReferenceRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Illegal Package Reference]]></name> <internalKey><![CDATA[IllegalPackageReference]]></internalKey> <description><![CDATA[<p> Checks for reference to any of the packages configured in <code>packageNames</code>. </p> <p>Note that you can use the standard rule properties, such as <code>applyToClassNames</code>, <code>doNotApplyToFileNames</code> and <code>applyToFilesMatching</code> to only apply this rule to a subset of all classes/files. These rule properties are described in <a href="http://codenarc.sourceforge.net/codenarc-configuring-rules.html#Standard_Properties_for_Configuring_Rules"> Standard Properties for Configuring Rules</a>. </p> <p>This rule can be useful for governance and enforcement of <architectural layering>. For instance, making sure that view or model classes, for instance, do not contain references to JDBC-specific packages (e.g. java.sql and javax.sql). </p> <p>Here is an example configuration of this rule used to ensure that JDBC packages/classes are only referenced within DAO classes: </p> <pre> ruleset { description "Example CodeNarc Ruleset" // ... IllegalPackageReference { name = 'UseJdbcOnlyInDaoClasses' priority = 2 packageNames = 'groovy.sql, java.sql, javax.sql' doNotApplyToClassNames = 'com.example.framework.dao.*, *Dao, *DaoImpl' description = 'Reference to JDBC packages should be restricted to DAO classes.' } } </pre> ]]></description> <tag>bug</tag> <param> <key>packageNames</key> <description><![CDATA[Specifies the comma-separated list of package names. The package name(s) may optionally include wildcard characters ('*' or '?'). Note that the '*' wildcard matches any sequence of zero or more characters in the package name, e.g. 'a.*' matches 'a.b' as well as 'a.b.c.d'. If packageNames is null or empty, do nothing. ]]></description> </param> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.generic.IllegalClassReferenceRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Illegal Class Reference]]></name> <internalKey><![CDATA[IllegalClassReference]]></internalKey> <description><![CDATA[<p> Checks for reference to any of the classes configured in <code>classNames</code>. </p> <p>Note that you can use the standard rule properties, such as <code>applyToClassNames</code>, <code>doNotApplyToFileNames</code> and <code>applyToFilesMatching</code> to only apply this rule to a subset of all classes/files. These rule properties are described in <a href="http://codenarc.sourceforge.net/codenarc-configuring-rules.html#Standard_Properties_for_Configuring_Rules"> Standard Properties for Configuring Rules</a>. </p> <p>This rule can be useful for governance and enforcement of <architectural layering>. For instance, making sure that view or model classes, for instance, do not contain references to DAO classes (e.g., *Dao). </p> <p>Here is an example configuration of this rule used to ensure that DAO classes are not referenced from within model classes: </p> <pre> ruleset { description "Example CodeNarc Ruleset" // ... IllegalClassReference { name = 'DoNotReferenceDaoFromModelClasses' priority = 2 classNames = '*Dao' applyToClassNames = 'com.example.model.*' description = 'Do not reference DAOs from model classes.' } } </pre> ]]></description> <tag>bug</tag> <param> <key>classNames</key> <description><![CDATA[Specifies the comma-separated list of (fully-qualified) class names. The class name(s) may optionally include wildcard characters ('*' or '?'). Note that the '*' wildcard matches any sequence of zero or more characters in the class/package name, e.g. 'a.*.MyClass' matches a.b.MyClass as well as a.b.c.d.MyClass. If classNames is null or empty, do nothing. ]]></description> </param> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.generic.IllegalClassMemberRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Illegal Class Member]]></name> <internalKey><![CDATA[IllegalClassMember]]></internalKey> <description><![CDATA[<p>Checks for classes containing fields/properties/methods matching configured illegal member modifiers or not matching any of the configured allowed member modifiers. </p> <p>Modifiers for fields and methods include: </p> ]]></description> <tag>bug</tag> <param> <key>allowedFieldModifiers</key> <description><![CDATA[Specifies one or more groups of whitespace-delimited modifier names (e.g. "public static" or "protected"). Multiple groups are separated by commas (e.g. "private final, protected"). If a field does not match all of the modifiers in any group, then trigger a violation. If null or empty, skip this check. ]]></description> </param> <param> <key>allowedMethodModifiers</key> <description><![CDATA[Specifies one or more groups of whitespace-delimited modifier names (e.g. "public static" or "protected"). Multiple groups are separated by commas (e.g. "private final, protected"). If a method does not match all of the modifiers in any group, then trigger a violation. If null or empty, skip this check. ]]></description> </param> <param> <key>allowedPropertyModifiers</key> <description><![CDATA[Specifies one or more groups of whitespace-delimited modifier names (e.g. "public static" or "protected"). Multiple groups are separated by commas (e.g. "private final, protected"). If a property does not match all of the modifiers in any group, then trigger a violation. If null or empty, skip this check. ]]></description> </param> <param> <key>ignoreMethodNames</key> <description><![CDATA[Specifies one or more (comma-separated) method names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> <param> <key>ignoreMethodsWithAnnotationNames</key> <description><![CDATA[Specifies one or more (comma-separated) annotation names that should be ignored (i.e., methods with those annotations should not cause a rule violation). The names may optionally contain wildcards (*,?). (Do not include the "@" in the annotation name ]]></description> </param> <param> <key>illegalFieldModifiers</key> <description><![CDATA[Specifies one or more groups of whitespace-delimited modifier names (e.g. "public static" or "protected"). Multiple groups are separated by commas (e.g. "private final, protected"). If a field matches all of the modifiers in any group, then trigger a violation. If null or empty, skip this check. ]]></description> </param> <param> <key>illegalMethodModifiers</key> <description><![CDATA[Specifies one or more groups of whitespace-delimited modifier names (e.g. "public static" or "protected"). Multiple groups are separated by commas (e.g. "private final, protected"). If a method matches all of the modifiers in any group, then trigger a violation. If null or empty, skip this check. ]]></description> </param> <param> <key>illegalPropertyModifiers</key> <description><![CDATA[Specifies one or more groups of whitespace-delimited modifier names (e.g. "public static" or "protected"). Multiple groups are separated by commas (e.g. "private final, protected"). If a property matches all of the modifiers in any group, then trigger a violation. If null or empty, skip this check. ]]></description> </param> </rule> <!-- since 0.20 --> <rule> <key>org.codenarc.rule.generic.IllegalStringRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Illegal String]]></name> <internalKey><![CDATA[IllegalString]]></internalKey> <description><![CDATA[<p>Checks for a specified illegal string within the source code. </p> <p>A RuleSet can contain any number of instances of this rule, but each should be configured with a unique rule <name> and <string>, and (optionally) customized <violationMessage> and <priority>. </p> <p><code>NOTE:</code> This rule applies to the text contents of an entire <file> rather than a specific <class>, so it does not support the <applyToClassNames> and <doNotApplyToClassNames> configuration properties. </p> ]]></description> <tag>bug</tag> <param> <key>string</key> <description><![CDATA[The String to check for. If null or empty then do nothing. ]]></description> </param> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.generic.IllegalSubclassRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Illegal Subclass]]></name> <internalKey><![CDATA[IllegalSubclass]]></internalKey> <description><![CDATA[<p>Checks for classes that extend one of the specified set of illegal superclasses. </p> <p>A RuleSet can contain any number of instances of this rule, but each should be configured with a unique rule <name> and <string>, and (optionally) customized <violationMessage> and <priority>. </p> ]]></description> <tag>bug</tag> <param> <key>superclassNames</key> <description><![CDATA[Specifies the comma-separated list of (fully-qualified) class names. The class name(s) may optionally include wildcard characters ('*' or '?'). Note that the '*' wildcard matches any sequence of zero or more characters in the class/package name, e.g. 'a.*.MyClass' matches a.b.MyClass as well as a.b.c.d.MyClass. If classNames is null or empty, do nothing. ]]></description> </param> </rule> <!-- grails rules --> <rule> <key>org.codenarc.rule.grails.GrailsPublicControllerMethodRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Grails Public Controller Method]]></name> <internalKey><![CDATA[GrailsPublicControllerMethod]]></internalKey> <description><![CDATA[<p> Rule that checks for public methods on Grails controller classes. Static methods are ignored. </p> <p>Grails controller actions and interceptors are defined as properties on the controller class. Public methods on a controller class are unnecessary. They break encapsulation and can be confusing. </p> <p>This rule sets the default value of <code>applyToFilesMatching</code> to only match files under the 'grails-app/controllers' folder. You can override this with a different regular expression value if appropriate. </p> <p>This rule also sets the default value of <code>applyToClassNames</code> to only match class names ending in 'Controller'. You can override this with a different class name pattern (String with wildcards) if appropriate. </p> ]]></description> <tag>grails</tag> <param> <key>ignoreMethodNames</key> <description><![CDATA[Specifies one or more (comma-separated) method names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> </rule> <rule> <key>org.codenarc.rule.grails.GrailsSessionReferenceRule</key> <severity>MINOR</severity> <name><![CDATA[Grails Session Reference]]></name> <internalKey><![CDATA[GrailsSessionReference]]></internalKey> <description><![CDATA[<p> Rule that checks for references to the <code>session</code> object from within Grails controller and taglib classes. </p> <p>This rule is intended as a "governance" rule to enable monitoring and controlling access to the <code>session</code> from within application source code. Storing objects in the <code>session</code> may inhibit scalability and/or performance and should be carefully considered. </p> <p>Note that this rule does not check for direct access to the <code>session</code> from within GSP (Groovy Server Pages) files. </p> <p>Enabling this rule may make most sense in a team environment where team members exhibit a broad range of skill and experience levels. Appropriate <code>session</code> access can be configured as exceptions to this rule by configuring either the <code>doNotApplyToFilenames</code> or <code>doNotApplyToFilesMatching</code> property of the rule. And, as always, it is easy to just <a href="http://codenarc.sourceforge.net/codenarc-configuring-rules.html#Turning_Off_A_Rule">turn off the rule</a> if it does not make sense it your environment. </p> <p>This rule sets the default value of <code>applyToFilesMatching</code> to only match files under the 'grails-app/controllers' or 'grails-app/taglib' folders. You can override this with a different regular expression value if appropriate. </p> ]]></description> <tag>grails</tag> </rule> <rule> <key>org.codenarc.rule.grails.GrailsServletContextReferenceRule</key> <severity>MINOR</severity> <name><![CDATA[Grails Servlet Context Reference]]></name> <internalKey><![CDATA[GrailsServletContextReference]]></internalKey> <description><![CDATA[<p>Rule that checks for references to the <code>servletContext</code> object from within Grails controller and taglib classes. </p> <p>This rule is intended as a "governance" rule to enable monitoring and controlling access to the <code>servletContext</code> from within application source code. Storing objects in the <code>servletContext</code> may inhibit scalability and/or performance and should be carefully considered. Furthermore, access to the <code>servletContext</code> is not synchronized, so reading/writing objects from the <code>servletConext</code> must be manually synchronized, as described in <a href="http://www.amazon.com/Definitive-Grails-Second-Experts-Development/dp/1590599950"> The Definitive Guide to Grails (2nd edition)</a>. </p> <p>Note that this rule does not check for direct access to the <code>servletContext</code> from within GSP (Groovy Server Pages) files. </p> <p>Enabling this rule may make most sense in a team environment where team members exhibit a broad range of skill and experience levels. Appropriate <code>servletContext</code> access can be configured as exceptions to this rule by configuring either the <code>doNotApplyToFilenames</code> or <code>doNotApplyToFilesMatching</code> property of the rule. And, as always, it is easy to just <a href="http://codenarc.sourceforge.net/codenarc-configuring-rules.html#Turning_Off_A_Rule">turn off the rule</a> if it does not make sense it your environment. </p> <p>This rule sets the default value of <code>applyToFilesMatching</code> to only match files under the 'grails-app/controllers' or 'grails-app/taglib' folders. You can override this with a different regular expression value if appropriate. </p> ]]></description> <tag>grails</tag> </rule> <rule> <key>org.codenarc.rule.grails.GrailsStatelessServiceRule</key> <severity>MINOR</severity> <name><![CDATA[Grails Stateless Service]]></name> <internalKey><![CDATA[GrailsStatelessService]]></internalKey> <description><![CDATA[<p>Checks for non-<code>final</code> fields on a Grails service class. Grails service classes are singletons by default, and so they should be reentrant. In most cases, this implies (or at least encourages) that they should be stateless. </p> <p>This rule ignores (i.e., does not cause violations for) the following: </p> ]]></description> <tag>grails</tag> <param> <key>ignoreFieldNames</key> </param> <param> <key>ignoreFieldTypes</key> </param> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.grails.GrailsDomainHasToStringRule</key> <severity>MINOR</severity> <name><![CDATA[Grails Domain Has To String]]></name> <internalKey><![CDATA[GrailsDomainHasToString]]></internalKey> <description><![CDATA[<p>Checks that Grails domain classes redefine <code>toString()</code>. </p> <p>Ignores classes annotated with <code>@ToString</code> or <code>@Canonical</code>. </p> <p>This rule sets the default value of <code>applyToFilesMatching</code> to only match files under the 'grails-app/domain' folder. You can override this with a different regular expression value if appropriate. </p> ]]></description> <tag>grails</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.grails.GrailsDomainHasEqualsRule</key> <severity>MINOR</severity> <name><![CDATA[Grails Domain Has Equals]]></name> <internalKey><![CDATA[GrailsDomainHasEquals]]></internalKey> <description><![CDATA[<p>Checks that Grails domain classes redefine <code>equals()</code>. </p> <p>Ignores classes annotated with <code>@EqualsAndHashCode</code> or <code>@Canonical</code>. </p> <p>This rule sets the default value of <code>applyToFilesMatching</code> to only match files under the 'grails-app/domain' folder. You can override this with a different regular expression value if appropriate. </p> ]]></description> <tag>grails</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.grails.GrailsDuplicateMappingRule</key> <severity>MINOR</severity> <name><![CDATA[Grails Duplicate Mapping]]></name> <internalKey><![CDATA[GrailsDuplicateMapping]]></internalKey> <description><![CDATA[<p> Check for duplicate name in a Grails domain class mapping. Duplicate names/entries are legal, but can be confusing and error-prone. </p> <p>NOTE: This rule does not check that the values of the entries are duplicated, only that there are two entries with the same name. </p> <p>Example of violations: </p> <pre> class Person { String firstName String lastName static mapping = { table 'people' firstName column: 'First_Name' lastName column: 'Last_Name' firstName column: 'First_Name' // violation table 'people2' // violation } } </pre> ]]></description> <tag>grails</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.grails.GrailsDuplicateConstraintRule</key> <severity>MINOR</severity> <name><![CDATA[Grails Duplicate Constraint]]></name> <internalKey><![CDATA[GrailsDuplicateConstraint]]></internalKey> <description><![CDATA[<p> Check for duplicate name in a Grails domain class constraints. Duplicate names/entries are legal, but can be confusing and error-prone. </p> <p>NOTE: This rule does not check that the values of the entries are duplicated, only that there are two entries with the same name. </p> <p>Example of violations: </p> <pre> class Person { String firstName String lastName static constraints = { firstName nullable:true lastName nullable:true, maxSize:30 firstName nullable:false // violation } } </pre> ]]></description> <tag>grails</tag> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.grails.GrailsDomainReservedSqlKeywordNameRule</key> <severity>MINOR</severity> <name><![CDATA[Grails Domain Reserved Sql Keyword Name]]></name> <internalKey><![CDATA[GrailsDomainReservedSqlKeywordName]]></internalKey> <description><![CDATA[<p>Forbids usage of SQL reserved keywords as class or field names in Grails domain classes. Naming a domain class (or its field) with such a keyword causes SQL schema creation errors and/or redundant table/column name mappings. </p> <p>Note: due to limited type information available during CodeNarc's operation, this rule will report fields of type <code>java.io.Serializable</code>, but not of its implementations. Please specify any implementations used as domain properties in <code>additionalHibernateBasicTypes</code>. </p> ]]></description> <tag>grails</tag> <param> <key>additionalHibernateBasicTypes</key> <description><![CDATA[Comma-separated list of simple class names of additional classes that Hibernate maps as basic types (creates a column for a field of such class). Add your custom basic types here. ]]></description> </param> <param> <key>additionalReservedSqlKeywords</key> <description><![CDATA[Comma-separated list of additional reserved SQL keywords (just in case the 337 keywords of nowadays SQL-* standards weren't enough). ]]></description> </param> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.grails.GrailsDomainWithServiceReferenceRule</key> <severity>MINOR</severity> <name><![CDATA[Grails Domain With Service Reference]]></name> <internalKey><![CDATA[GrailsDomainWithServiceReference]]></internalKey> <description><![CDATA[<p>Checks that Grails Domain classes do not have Service classes injected. </p> <p>This rule sets the default value of <code>applyToFilesMatching</code> to only match files under the 'grails-app/domain' folder. You can override this with a different regular expression value if appropriate. </p> ]]></description> <tag>grails</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.grails.GrailsMassAssignmentRule</key> <severity>MINOR</severity> <name><![CDATA[Grails Mass Assignment]]></name> <internalKey><![CDATA[GrailsMassAssignment]]></internalKey> <description><![CDATA[<p>Untrusted input should not be allowed to set arbitrary object fields without restriction. </p> <p>Example of violations: </p> <pre> // Person would be a grails domain object def person = new Person(params) person.save() // or using .properties def person = Person.get(1) person.properties = params person.save() </pre> ]]></description> <tag>grails</tag> </rule> <!-- imports rules --> <rule> <key>org.codenarc.rule.imports.DuplicateImportRule</key> <severity>MAJOR</severity> <name><![CDATA[Duplicate Import]]></name> <internalKey><![CDATA[DuplicateImport]]></internalKey> <description><![CDATA[<p>Checks for a duplicate <import> statements. </p> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.imports.ImportFromSamePackageRule</key> <severity>MAJOR</severity> <name><![CDATA[Import From Same Package]]></name> <internalKey><![CDATA[ImportFromSamePackage]]></internalKey> <description><![CDATA[<p>Checks for an <import> of a class that is within the same package as the importing class. </p> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.imports.UnnecessaryGroovyImportRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Groovy Import]]></name> <internalKey><![CDATA[UnnecessaryGroovyImport]]></internalKey> <description><![CDATA[<p>Checks for an <import> from any package that is already automatically imported for Groovy files. A Groovy file does not need to include an import for classes from <java.lang>, <java.util>, <java.io>, <java.net>, <groovy.lang> and <groovy.util>, as well as the classes <java.math.BigDecimal> and <java.math.BigInteger>. </p> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.imports.UnusedImportRule</key> <severity>MAJOR</severity> <name><![CDATA[Unused Import]]></name> <internalKey><![CDATA[UnusedImport]]></internalKey> <description><![CDATA[<p>Checks for <import> statements for classes that are never referenced within the source file. Also checks static imports. </p> <p>Known limitations: </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.imports.ImportFromSunPackagesRule</key> <severity>MINOR</severity> <name><![CDATA[Import From Sun Packages]]></name> <internalKey><![CDATA[ImportFromSunPackages]]></internalKey> <description><![CDATA[<p>Avoid importing anything from the 'sun.*' packages. These packages are not portable and are likely to change.</p> <p>Example of violations: </p> <pre> import sun.misc.foo import sun.misc.foo as Foo public class MyClass{} </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.imports.MisorderedStaticImportsRule</key> <severity>MAJOR</severity> <name><![CDATA[Misordered Static Imports]]></name> <internalKey><![CDATA[MisorderedStaticImports]]></internalKey> <description><![CDATA[<p>Checks for static <import> statements which should never be after nonstatic imports.</p> <p>This rule has one property <code>comesBefore</code>, which defaults to true. If you like your static imports to come after the others, then set this property to false. </p> <p>Examples of violations: </p> <pre> import my.something.another import static foo.bar public class MyClass{} </pre> ]]></description> <tag>bug</tag> <param> <key>comesBefore</key> <description><![CDATA[If you like your static imports to come after the others, then set this property to false. ]]></description> <defaultValue>true</defaultValue> </param> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.imports.NoWildcardImportsRule</key> <severity>MAJOR</severity> <name><![CDATA[No Wildcard Imports]]></name> <internalKey><![CDATA[NoWildcardImports]]></internalKey> <description><![CDATA[<p>Wildcard imports, static or otherwise, should not be used. </p> <p>Example of violations: </p> <pre> import my.something.* import static foo.bar.* public class MyClass{} </pre> ]]></description> <tag>bug</tag> </rule> <!-- junit rules --> <rule> <key>org.codenarc.rule.junit.JUnitAssertAlwaysFailsRule</key> <severity>MINOR</severity> <name><![CDATA[JUnit Assert Always Fails]]></name> <internalKey><![CDATA[JUnitAssertAlwaysFails]]></internalKey> <description><![CDATA[<p>Rule that checks for JUnit <<<assert()>>> method calls with constant or literal arguments such that theassertion always fails. This includes: </p> ]]></description> <tag>junit</tag> </rule> <rule> <key>org.codenarc.rule.junit.JUnitAssertAlwaysSucceedsRule</key> <severity>MINOR</severity> <name><![CDATA[JUnit Assert Always Succeeds]]></name> <internalKey><![CDATA[JUnitAssertAlwaysSucceeds]]></internalKey> <description><![CDATA[<p>Rule that checks for JUnit <code>assert()</code> method calls with constant arguments such that the assertion always succeeds. This includes: </p> ]]></description> <tag>junit</tag> </rule> <rule> <key>org.codenarc.rule.junit.JUnitPublicNonTestMethodRule</key> <severity>MINOR</severity> <name><![CDATA[JUnit Public Non Test Method]]></name> <internalKey><![CDATA[JUnitPublicNonTestMethod]]></internalKey> <description><![CDATA[<p>Rule that checks if a JUnit test class contains public methods other than standard test methods, JUnit framework methods or methods with JUnit annotations. </p> <p>The following public methods are ignored by this rule: </p> ]]></description> <tag>junit</tag> </rule> <rule> <key>org.codenarc.rule.junit.JUnitSetUpCallsSuperRule</key> <severity>MINOR</severity> <name><![CDATA[JUnit Set Up Calls Super]]></name> <internalKey><![CDATA[JUnitSetUpCallsSuper]]></internalKey> <description><![CDATA[<p>Rule that checks that if the JUnit <code>setUp</code> method is defined, that it includes a call to <code>super.setUp()</code>. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> ]]></description> <tag>junit</tag> </rule> <rule> <key>org.codenarc.rule.junit.JUnitTearDownCallsSuperRule</key> <severity>MINOR</severity> <name><![CDATA[JUnit Tear Down Calls Super]]></name> <internalKey><![CDATA[JUnitTearDownCallsSuper]]></internalKey> <description><![CDATA[<p>Rule that checks that if the JUnit <code>tearDown</code> method is defined, that it includes a call to <code>super.tearDown()</code>. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> ]]></description> <tag>junit</tag> </rule> <rule> <key>org.codenarc.rule.junit.JUnitUnnecessarySetUpRule</key> <severity>MAJOR</severity> <name><![CDATA[JUnit Unnecessary Set Up]]></name> <internalKey><![CDATA[JUnitUnnecessarySetUp]]></internalKey> <description><![CDATA[<p>Rule that checks checks for JUnit <code>setUp()</code> methods that contain only a call to <code>super.setUp()</code>. The method is then unnecessary. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> <p>Here is an example of a violation: </p> <pre> class MyTest extends TestCase { void setUp() { // violation super.setUp() } } </pre> ]]></description> <tag>junit</tag> </rule> <rule> <key>org.codenarc.rule.junit.JUnitUnnecessaryTearDownRule</key> <severity>MAJOR</severity> <name><![CDATA[JUnit Unnecessary Tear Down]]></name> <internalKey><![CDATA[JUnitUnnecessaryTearDown]]></internalKey> <description><![CDATA[<p>Rule that checks checks for JUnit <code>tearDown()</code> methods that contain only a call to <code>super.tearDown()</code>. The method is then unnecessary. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> <p>Here is an example of a violation: </p> <pre> class MyTest extends TestCase { void tearDown() { // violation super.tearDown() } } </pre> ]]></description> <tag>junit</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.junit.JUnitStyleAssertionsRule</key> <severity>MAJOR</severity> <name><![CDATA[JUnit Style Assertions]]></name> <internalKey><![CDATA[JUnitStyleAssertions]]></internalKey> <description><![CDATA[<p>This rule detects calling JUnit style assertions like <code>assertEquals</code>, <code>assertTrue</code>, <code>assertFalse</code>, <code>assertNull</code>, <code>assertNotNull</code>. Groovy 1.7 ships with a feature called the "power assert", which is an assert statement with better error reporting. This is preferable to the JUnit assertions. </p> ]]></description> <tag>junit</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.junit.UseAssertEqualsInsteadOfAssertTrueRule</key> <severity>MAJOR</severity> <name><![CDATA[Use Assert Equals Instead Of Assert True]]></name> <internalKey><![CDATA[UseAssertEqualsInsteadOfAssertTrue]]></internalKey> <description><![CDATA[<p>This rule detects JUnit assertions in object equality. These assertions should be made by more specific methods, like <code>assertEquals</code>. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> ]]></description> <tag>junit</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.junit.UseAssertFalseInsteadOfNegationRule</key> <severity>MINOR</severity> <name><![CDATA[Use Assert False Instead Of Negation]]></name> <internalKey><![CDATA[UseAssertFalseInsteadOfNegation]]></internalKey> <description><![CDATA[<p>In unit tests, if a condition is expected to be false then there is no sense using <code>assertTrue</code> with the negation operator. For instance, <code>assertTrue(!condition)</code> can always be simplified to <code>assertFalse(condition)</code>. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> ]]></description> <tag>junit</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.junit.UseAssertTrueInsteadOfAssertEqualsRule</key> <severity>MAJOR</severity> <name><![CDATA[Use Assert True Instead Of Assert Equals]]></name> <internalKey><![CDATA[UseAssertTrueInsteadOfAssertEquals]]></internalKey> <description><![CDATA[<p>This rule detects JUnit calling <code>assertEquals</code> where the first parameter is a boolean. These assertions should be made by more specific methods, like <code>assertTrue</code> or <code>assertFalse</code>. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> All of the following examples can be simplified to assertTrue or remove the true literal: </p> <pre> assertEquals(true, foo()) assertEquals("message", true, foo()) assertEquals(foo(), true) assertEquals("message", foo(), true) assertEquals(false, foo()) assertEquals("message", false, foo()) assertEquals(foo(), false) assertEquals("message", foo(), false) assert true == foo() // violation only if checkAssertStatements == true assert foo() == true : "message" // violation only if checkAssertStatements == true assert false == foo() // violation only if checkAssertStatements == true assert foo() == false : "message" // violation only if checkAssertStatements == true </pre> ]]></description> <tag>junit</tag> <param> <key>checkAssertStatements</key> <description><![CDATA[If true, then also check assert statements, e.g. assert x == true. ]]></description> <defaultValue>false</defaultValue> </param> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.junit.UseAssertNullInsteadOfAssertEqualsRule</key> <severity>MAJOR</severity> <name><![CDATA[Use Assert Null Instead Of Assert Equals]]></name> <internalKey><![CDATA[UseAssertNullInsteadOfAssertEquals]]></internalKey> <description><![CDATA[<p>This rule detects JUnit calling <code>assertEquals</code> where the first or second parameter is <code>null</code>. These assertion should be made against the <code>assertNull</code> method instead. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> ]]></description> <tag>junit</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.junit.UseAssertSameInsteadOfAssertTrueRule</key> <severity>MAJOR</severity> <name><![CDATA[Use Assert Same Instead Of Assert True]]></name> <internalKey><![CDATA[UseAssertSameInsteadOfAssertTrue]]></internalKey> <description><![CDATA[<p>This rule detects JUnit calling <code>assertTrue</code> or <code>assertFalse</code> where the first or second parameter is an <code>Object#is()</code> call testing for reference equality. These assertion should be made against the <code>assertSame</code> or <code>assertNotSame</code> method instead. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> ]]></description> <tag>junit</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.junit.JUnitFailWithoutMessageRule</key> <severity>MINOR</severity> <name><![CDATA[JUnit Fail Without Message]]></name> <internalKey><![CDATA[JUnitFailWithoutMessage]]></internalKey> <description><![CDATA[<p>This rule detects JUnit calling the <code>fail()</code> method without an argument. For better error reporting you should always provide a message. </p> ]]></description> <tag>junit</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.junit.UseAssertTrueInsteadOfNegationRule</key> <severity>MINOR</severity> <name><![CDATA[Use Assert True Instead Of Negation]]></name> <internalKey><![CDATA[UseAssertTrueInsteadOfNegation]]></internalKey> <description><![CDATA[<p>In unit tests, if a condition is expected to be true then there is no sense using <code>assertFalse</code> with the negation operator. For instance, <code>assertFalse(!condition)</code> can always be simplified to <code>assertTrue(condition)</code>. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> ]]></description> <tag>junit</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.junit.JUnitTestMethodWithoutAssertRule</key> <severity>MINOR</severity> <name><![CDATA[JUnit Test Method Without Assert]]></name> <internalKey><![CDATA[JUnitTestMethodWithoutAssert]]></internalKey> <description><![CDATA[<p>This rule searches for test methods that do not contain assert statements. Either the test method is missing assert statements, which is an error, or the test method contains custom assert statements that do not follow a proper assert naming convention. Test methods are defined as public void methods that begin with the work test or have a @Test annotation. By default this rule applies to the default test class names, but this can be changed using the rule's applyToClassNames property. An assertion is defined as either using the <code>assert</code> keyword or invoking a method that starts with the work assert, like assertEquals, assertNull, or assertMyClassIsSimilar. Also, any method named <code>should.*</code> also counts as an assertion so that <code>shouldFail</code> methods do not trigger an assertion, any method that starts with <code>fail</code> counts as an assertion, and any method that starts with <code>verify</code> counts as an assertion. Since version 0.23 CodeNarc has support for JUnit's ExpectedException. </p> <p>What counts as an assertion method can be overridden using the assertMethodPatterns property of the rule. The default value is this comma separated list of regular expressions: </p> <pre> String assertMethodPatterns = 'assert.*,should.*,fail.*,verify.*,expect.*' </pre> <pre> 'assert.*,should.*,fail.*,verify.*,ensure.*' </pre> ]]></description> <tag>junit</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.junit.ChainedTestRule</key> <severity>MINOR</severity> <name><![CDATA[Chained Test]]></name> <internalKey><![CDATA[ChainedTest]]></internalKey> <description><![CDATA[<p>A test method that invokes another test method is a chained test; the methods are dependent on one another. Tests should be isolated, and not be dependent on one another. </p> <p>Example of violations: </p> <pre> class MyTest extends GroovyTestCase { public void testFoo() { // violations, calls test method on self 5.times { testBar() } 5.times { this.testBar() } // OK, no violation: one arg method is not actually a test method 5.times { testBar(it) } } private static void assertSomething() { testBar() // violation, even if in helper method this.testBar() // violation, even if in helper method } public void testBar() { // ... } } </pre> ]]></description> <tag>junit</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.junit.CoupledTestCaseRule</key> <severity>MINOR</severity> <name><![CDATA[Coupled Test Case]]></name> <internalKey><![CDATA[CoupledTestCase]]></internalKey> <description><![CDATA[<p>This rule finds test cases that are coupled to other test cases, either by invoking static methods on another test case or by creating instances of another test case. If you require shared logic in test cases then extract that logic to a new class where it can properly be reused. Static references to methods on the current test class are ignored. </p> <p>Example of violations: </p> <pre> class MyTest extends GroovyTestCase { public void testMethod() { // violation, static method call to other test MyOtherTest.helperMethod() // violation, instantiation of another test class new MyOtherTest() // no violation; same class def input = MyTest.getResourceAsStream('sample.txt') } } </pre> ]]></description> <tag>junit</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.junit.UnnecessaryFailRule</key> <severity>MINOR</severity> <name><![CDATA[Unnecessary Fail]]></name> <internalKey><![CDATA[UnnecessaryFail]]></internalKey> <description><![CDATA[<p>In a unit test, catching an exception and immediately calling Assert.fail() is pointless and hides the stack trace. It is better to rethrow the exception or not catch the exception at all. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> <p>Example of violations: </p> <pre> public void testSomething() { try { something() } catch (Exception e) { fail(e.message) } try { something() } catch (Exception e) { fail() } } </pre> ]]></description> <tag>junit</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.junit.SpockIgnoreRestUsedRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Spock Ignore Rest Used]]></name> <internalKey><![CDATA[SpockIgnoreRestUsed]]></internalKey> <description><![CDATA[<p> If Spock's <code>@IgnoreRest</code> annotation appears on any method, all non-annotated test methods are not executed. This behaviour is almost always unintended. It's fine to use @IgnoreRest locally during development, but when committing code, it should be removed. </p> <p>The <specificationClassNames> and <specificationSuperclassNames> properties determine which classes are considered Spock <Specification> classes. </p> <p>Example of violations: </p> <pre> public class MySpec extends spock.lang.Specification { @spock.lang.IgnoreRest def "my first feature"() { expect: false } def "my second feature"() { given: def a = 2 when: a *= 2 then: a == 4 } } </pre> ]]></description> <tag>junit</tag> <param> <key>specificationClassNames</key> <description><![CDATA[Specifies one or more (comma-separated) class names that should be treated as Spock Specification classes. The class names may optionally contain wildcards (*,?), e.g. "*Spec". ]]></description> </param> <param> <key>specificationSuperclassNames</key> <description><![CDATA[Specifies one or more (comma-separated) class names that should be treated as Spock Specification superclasses. In other words, a class that extends a matching class name is considered a Spock Specification . The class names may optionally contain wildcards (*,?), e.g. "*Spec". ]]></description> <defaultValue>*Specification</defaultValue> </param> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.junit.JUnitLostTestRule</key> <severity>MINOR</severity> <name><![CDATA[JUnit Lost Test]]></name> <internalKey><![CDATA[JUnitLostTest]]></internalKey> <description><![CDATA[<p>This rule checks for classes that import JUnit 4 classes and contain a <code>public</code>, instance, <code>void</code>, no-arg method named <test>* that is not annotated with the JUnit 4 <code>@Test</code> annotation. </p> <p>Note: This rule should be disabled for Grails 2.x projects, since the Grails test framework can use AST Transformations to automatically annotate test methods. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> <p>Example of violations: </p> <pre> import org.junit.Test class MyTestCase { void testMe() { } // missing @Test annotation } </pre> ]]></description> <tag>junit</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.junit.JUnitUnnecessaryThrowsExceptionRule</key> <severity>MAJOR</severity> <name><![CDATA[JUnit Unnecessary Throws Exception]]></name> <internalKey><![CDATA[JUnitUnnecessaryThrowsException]]></internalKey> <description><![CDATA[<p> Check for <code>throws</code> clauses on JUnit test methods. That is not necessary in Groovy. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> <p>Example of violations: </p> <pre> @Test void shouldDoStuff() throws Exception { } // violation @BeforeClass void initialize() throws Exception { } // violation @Before void setUp() throws RuntimeException { } // violation @After void tearDown() throws Exception { } // violation @AfterClass void cleanUp() throws Exception { } // violation @Ignore void ignored() throws Exception { } // violation class MyTest extends GroovyTestCase { void test1() throws Exception { } // violation public void test2() throws IOException { } // violation } </pre> ]]></description> <tag>junit</tag> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.junit.JUnitPublicFieldRule</key> <severity>MAJOR</severity> <name><![CDATA[JUnit Public Field]]></name> <internalKey><![CDATA[JUnitPublicField]]></internalKey> <description><![CDATA[<p>Checks for public fields on a JUnit test class. There is usually no reason to have a public field (even a constant) on a test class. </p> <p>Fields within interfaces and fields annotated with @Rule are ignored. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> <p>Example of violations: </p> <pre> import org.junit.Test class MyTestCase { public int count // violation public static final MAX_VALUE = 1000 // violation @Test void testMe() { } } </pre> ]]></description> <tag>junit</tag> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.junit.JUnitAssertEqualsConstantActualValueRule</key> <severity>MINOR</severity> <name><![CDATA[JUnit Assert Equals Constant Actual Value]]></name> <internalKey><![CDATA[JUnitAssertEqualsConstantActualValue]]></internalKey> <description><![CDATA[<p>Reports usages of <code>org.junit.Assert.assertEquals([message,] expected, actual)</code> where the <code>actual</code> parameter is a constant or a literal. Most likely it was intended to be the <code>expected</code> value. </p> <p>NOTE: This is a <a href="http://codenarc.sourceforge.net/codenarc-enhanced-classpath-rules.html">CodeNarc Enhanced Classpath Rule</a>. It requires <code>CodeNarc</code> to have the application classes being analyzed, as well as any referenced classes, on the classpath. </p> <p>Example of violations: </p> <pre> assertEquals(result, 2) assertEquals("Message", result, 2) assertEquals(result, 2.3d, 0.5d) assertEquals("Message", result, 2.3d, 0.5d) </pre> ]]></description> <tag>junit</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.junit.JUnitPublicPropertyRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[JUnit Public Property]]></name> <internalKey><![CDATA[JUnitPublicProperty]]></internalKey> <description><![CDATA[<p>Checks for public properties defined on JUnit test classes. There is typically no need to expose a public property (with public <getter> and <setter> methods) on a test class. </p> <p>This rule sets the default value of the <applyToClassNames> property to only match class names ending in 'Test', 'Tests' or 'TestCase'. </p> <p>Example of violations: </p> <pre> import org.junit.Test class MyTestCase { static String id // violation def helper // violation String name // violation @Test void testMe() { } } </pre> ]]></description> <tag>junit</tag> <param> <key>ignorePropertyNames</key> <description><![CDATA[Specifies one or more (comma-separated) property names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> </rule> <!-- logging rules --> <rule> <key>org.codenarc.rule.logging.PrintlnRule</key> <severity>MINOR</severity> <name><![CDATA[Println]]></name> <internalKey><![CDATA[Println]]></internalKey> <description><![CDATA[<p>Checks for calls to <code>this.print()</code>, <code>this.println()</code> or <code>this.printf()</code>. Consider using a standard logging facility instead. </p> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.logging.PrintStackTraceRule</key> <severity>MINOR</severity> <name><![CDATA[Print Stack Trace]]></name> <internalKey><![CDATA[PrintStackTrace]]></internalKey> <description><![CDATA[<p>Checks for calls to <code>Throwable.printStackTrace()</code> or <code>StackTraceUtils.printSanitizedStackTrace(Throwable)</code>. Consider using a standard logging facility instead. </p> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.logging.SystemErrPrintRule</key> <severity>MINOR</severity> <name><![CDATA[System Err Print]]></name> <internalKey><![CDATA[SystemErrPrint]]></internalKey> <description><![CDATA[<p>Checks for calls to <code>System.err.print()</code>, <code>System.err.println()</code> or <code>System.err.printf()</code>. Consider using a standard logging facility instead. </p> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.logging.SystemOutPrintRule</key> <severity>MINOR</severity> <name><![CDATA[System Out Print]]></name> <internalKey><![CDATA[SystemOutPrint]]></internalKey> <description><![CDATA[<p>Checks for calls to <code>System.out.print()</code>, <code>System.out.println()</code> or <code>System.out.printf()</code>. Consider using a standard logging facility instead. </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.logging.LoggerForDifferentClassRule</key> <severity>MINOR</severity> <name><![CDATA[Logger For Different Class]]></name> <internalKey><![CDATA[LoggerForDifferentClass]]></internalKey> <description><![CDATA[<p>Checks for instantiating a logger for a class other than the current class. Checks for logger instantiations for <code>Log4J</code>, <code>SLF4J</code>, <code>Logback</code>, <code>Apache Commons Logging</code> and <code>Java Logging API (java.util.logging)</code>. </p> <p>This rule contains a parameter <code>allowDerivedClasses</code>. When set, a logger may be created about this.getClass(). </p> <p>Limitations: </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.logging.LoggingSwallowsStacktraceRule</key> <severity>MINOR</severity> <name><![CDATA[Logging Swallows Stacktrace]]></name> <internalKey><![CDATA[LoggingSwallowsStacktrace]]></internalKey> <description><![CDATA[<p>If you are logging an exception then the proper API is to call error(Object, Throwable), which will log the message and the exception stack trace. If you call error(Object) then the stacktrace may not be logged. </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.logging.LoggerWithWrongModifiersRule</key> <severity>MINOR</severity> <name><![CDATA[Logger With Wrong Modifiers]]></name> <internalKey><![CDATA[LoggerWithWrongModifiers]]></internalKey> <description><![CDATA[<p>Logger objects should be declared private, static and final. </p> <p>This rule has a property: <code>allowProtectedLogger</code>, which defaults to false. Set it to true if you believe subclasses should have access to a Logger in a parent class and that Logger should be declared protected or public. </p> <p>This rule has a property: <code>allowNonStaticLogger</code>, which defaults to false. Set it to true if you believe a logger should be allowed to be non-static. </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.logging.MultipleLoggersRule</key> <severity>MINOR</severity> <name><![CDATA[Multiple Loggers]]></name> <internalKey><![CDATA[MultipleLoggers]]></internalKey> <description><![CDATA[<p>This rule catches classes that have more than one logger object defined. Typically, a class has zero or one logger objects. </p> ]]></description> <tag>bug</tag> </rule> <!-- naming rules --> <rule> <key>org.codenarc.rule.naming.AbstractClassNameRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Abstract Class Name]]></name> <internalKey><![CDATA[AbstractClassName]]></internalKey> <description><![CDATA[<p>Verifies that the name of an abstract class matches the regular expression specified in the <code>regex</code> property. If that property is null or empty, then this rule is not applied (i.e., it does nothing). It defaults to null, so this rule must be explicitly configured to be active. This rule ignores interfaces and is applied only to abstract classes. </p> ]]></description> <tag>bug</tag> <param> <key>regex</key> <description><![CDATA[Specifies the regular expression used to validate the abstract class name. If null or empty, then this rule does nothing. ]]></description> </param> </rule> <rule> <key>org.codenarc.rule.naming.ClassNameRule</key> <severity>MINOR</severity> <name><![CDATA[Class Name]]></name> <internalKey><![CDATA[ClassName]]></internalKey> <description><![CDATA[<p>Verifies that the name of a class matches a regular expression. By default it checks that the class name starts with an uppercase letter and is followed by zero or more word characters (letters, numbers or underscores) or dollar signs ($). </p> ]]></description> <tag>bug</tag> <param> <key>regex</key> <description><![CDATA[Specifies the regular expression used to validate the class name. It is required and cannot be null or empty. ]]></description> <defaultValue>([A-Z]\w*\$?)*</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.naming.FieldNameRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Field Name]]></name> <internalKey><![CDATA[FieldName]]></internalKey> <description><![CDATA[<p>Verifies that the name of each field matches a regular expression. By default it checks that fields that are not <static final> have field names that start with a lowercase letter and contains only letters or numbers. By default, <static final> field names start with an uppercase letter and contain only uppercase letters, numbers and underscores. </p> <p><code>NOTE:</code> This rule checks only regular <fields> of a class, not <properties>. In Groovy, <properties> are fields declared with no access modifier (public, protected, private). Thus, this rule only checks fields that specify an access modifier. For naming of <properties>, see <code>PropertyNameRule</code>. </p> <p>The order of precedence for the regular expression properties is: <code>staticFinalRegex</code>, <code>finalRegex</code>, <code>staticRegex</code> and finally <code>regex</code>. In other words, the first regex in that list matching the modifiers for the field is the one that is applied for the field name validation. </p> ]]></description> <tag>bug</tag> <param> <key>finalRegex</key> <description><![CDATA[Specifies the regular expression used to validate final field names. It is optional. If not set, then final fields that are non-static are validated using regex. ]]></description> </param> <param> <key>ignoreFieldNames</key> <description><![CDATA[Specifies one or more (comma-separated) field names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> <defaultValue>serialVersionUID</defaultValue> </param> <param> <key>regex</key> <description><![CDATA[Specifies the default regular expression used to validate the field name. It is required and cannot be null or empty. ]]></description> <defaultValue>[a-z][a-zA-Z0-9]*</defaultValue> </param> <param> <key>staticFinalRegex</key> <description><![CDATA[Specifies the regular expression used to validate static final field names. It is optional. If not set, then static final fields are validated using finalRegex, staticRegex or regex. ]]></description> <defaultValue>[A-Z][A-Z0-9_]*</defaultValue> </param> <param> <key>staticRegex</key> <description><![CDATA[Specifies the regular expression used to validate static field names. It is optional. If not set, then static fields that are non-final are validated using regex. ]]></description> </param> </rule> <rule> <key>org.codenarc.rule.naming.InterfaceNameRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Interface Name]]></name> <internalKey><![CDATA[InterfaceName]]></internalKey> <description><![CDATA[<p>Verifies that the name of an interface matches the regular expression specified in the <code>regex</code> property. If that property is null or empty, then this rule is not applied (i.e., it does nothing). It defaults to null, so this rule must be explicitly configured to be active. </p> ]]></description> <tag>bug</tag> <param> <key>regex</key> <description><![CDATA[Specifies the regular expression used to validate the name of an interface. If null or empty, then this rule does nothing. ]]></description> </param> </rule> <rule> <key>org.codenarc.rule.naming.MethodNameRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Method Name]]></name> <internalKey><![CDATA[MethodName]]></internalKey> <description><![CDATA[<p>Verifies that the name of each method matches a regular expression. By default it checks that the method name starts with a lowercase letter. Implicit method names are ignored (i.e., 'main' and 'run' methods automatically created for Groovy scripts). </p> ]]></description> <tag>bug</tag> <param> <key>ignoreMethodNames</key> <description><![CDATA[Specifies one or more (comma-separated) method names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> <param> <key>regex</key> <description><![CDATA[Specifies the regular expression used to validate the method name. It is required and cannot be null or empty. ]]></description> <defaultValue>[a-z]\w*</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.naming.PackageNameRule</key> <severity>MINOR</severity> <name><![CDATA[Package Name]]></name> <internalKey><![CDATA[PackageName]]></internalKey> <description><![CDATA[<p>Verifies that the package name of a class matches a regular expression. By default it checks that the package name consists of only lowercase letters and numbers, separated by periods. </p> ]]></description> <tag>bug</tag> <param> <key>packageNameRequired</key> <description><![CDATA[Indicates whether a package name declaration is required for all classes. ]]></description> <defaultValue>false</defaultValue> </param> <param> <key>regex</key> <description><![CDATA[Specifies the regular expression used to validate the package name. It is required and cannot be null or empty. ]]></description> <defaultValue>[a-z]+[a-z0-9]*(\.[a-z0-9]+)*</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.naming.ParameterNameRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Parameter Name]]></name> <internalKey><![CDATA[ParameterName]]></internalKey> <description><![CDATA[<p>Verifies that the name of each parameter matches a regular expression. This rule applies to method parameters, constructor parameters and closure parameters. By default it checks that parameter names start with a lowercase letter and contains only letters or numbers. </p> ]]></description> <tag>bug</tag> <param> <key>ignoreParameterNames</key> <description><![CDATA[Specifies one or more (comma-separated) parameter names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> <param> <key>regex</key> <description><![CDATA[Specifies the regular expression used to validate the parameter name. It is required and cannot be null or empty. ]]></description> <defaultValue>[a-z][a-zA-Z0-9]*</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.naming.PropertyNameRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Property Name]]></name> <internalKey><![CDATA[PropertyName]]></internalKey> <description><![CDATA[<p>Verifies that the name of each property matches a regular expression. By default it checks that property names (other than <static final>) start with a lowercase letter and contains only letters or numbers. By default, <static final> property names start with an uppercase letter and contain only uppercase letters, numbers and underscores. </p> <p><code>NOTE:</code> This rule checks only <properties> of a class, not regular <fields>. In Groovy, <properties> are fields declared with no access modifier (public, protected, private). For naming of regular <fields>, see <code>FieldNameRule</code>. </p> <p>The order of precedence for the regular expression properties is: <code>staticFinalRegex</code>, <code>finalRegex</code>, <code>staticRegex</code> and finally <code>regex</code>. In other words, the first regex in that list matching the modifiers for the property is the one that is applied for the field name validation. </p> ]]></description> <tag>bug</tag> <param> <key>finalRegex</key> <description><![CDATA[Specifies the regular expression used to validate final property names. It is optional. If not set, then final properties that are non-static are validated using regex. ]]></description> </param> <param> <key>ignorePropertyNames</key> <description><![CDATA[Specifies one or more (comma-separated) property names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> <param> <key>regex</key> <description><![CDATA[Specifies the default regular expression used to validate the property name. It is required and cannot be null or empty. ]]></description> <defaultValue>[a-z][a-zA-Z0-9]*</defaultValue> </param> <param> <key>staticFinalRegex</key> <description><![CDATA[Specifies the regular expression used to validate static final property names. It is optional. If not set, then static final property are validated using finalRegex, staticRegex or regex. ]]></description> <defaultValue>[A-Z][A-Z0-9_]*</defaultValue> </param> <param> <key>staticRegex</key> <description><![CDATA[Specifies the regular expression used to validate static property names. It is optional. If not set, then static properties that are non-final are validated using regex. ]]></description> </param> </rule> <rule> <key>org.codenarc.rule.naming.VariableNameRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Variable Name]]></name> <internalKey><![CDATA[VariableName]]></internalKey> <description><![CDATA[<p>Verifies that the name of each variable matches a regular expression. By default it checks that non-<code>final</code> variable names start with a lowercase letter and contains only letters or numbers. By default, <code>final</code> variable names start with an uppercase letter and contain only uppercase letters, numbers and underscores. </p> ]]></description> <tag>bug</tag> <param> <key>finalRegex</key> <description><![CDATA[Specifies the regular expression used to validate final variable names. It is optional. If not set, then regex is used to validate final variable names. ]]></description> <defaultValue>[A-Z][A-Z0-9_]*</defaultValue> </param> <param> <key>ignoreVariableNames</key> <description><![CDATA[Specifies one or more (comma-separated) variable names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> <param> <key>regex</key> <description><![CDATA[Specifies the default regular expression used to validate the variable name. It is required and cannot be null or empty. ]]></description> <defaultValue>[a-z][a-zA-Z0-9]*</defaultValue> </param> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.naming.ConfusingMethodNameRule</key> <severity>MINOR</severity> <name><![CDATA[Confusing Method Name]]></name> <internalKey><![CDATA[ConfusingMethodName]]></internalKey> <description><![CDATA[<p>Checks for very confusing method names. The referenced methods have names that differ only by capitalization. This is very confusing because if the capitalization were identical then one of the methods would override the other. </p> <p>Also, violations are triggered when methods and fields have very similar names. </p> <pre> class MyClass { int total int total() { 1 } } </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.naming.ObjectOverrideMisspelledMethodNameRule</key> <severity>MINOR</severity> <name><![CDATA[Object Override Misspelled Method Name]]></name> <internalKey><![CDATA[ObjectOverrideMisspelledMethodName]]></internalKey> <description><![CDATA[<p> Verifies that the names of the most commonly overridden methods of <code>Object</code>: <code>equals</code>, <code>hashCode</code> and <code>toString</code>, are correct. </p> <p>Here are some examples of code that produces violations: </p> <pre> boolean equal(Object o) {} // violation boolean equal(int other) {} // ok; wrong param type boolean equal(Object o, int other) {} // ok; too many params boolean equaLS(Object o) {} // violation int hashcode() {} // violation int hashCOde() {} // violation int hashcode(int value) {} // ok; not empty params String tostring() {} // violation String toSTring() {} // violation String tostring(int value) {} // ok; not empty params </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.naming.FactoryMethodNameRule</key> <severity>MINOR</severity> <name><![CDATA[Factory Method Name]]></name> <internalKey><![CDATA[FactoryMethodName]]></internalKey> <description><![CDATA[<p>A factory method is a method that creates objects, and they are typically named either buildFoo(), makeFoo(), or createFoo(). This rule enforces that only one naming convention is used. It defaults to allowing makeFoo(), but that can be changed using the property <code>regex</code>. The regex is a negative expression; it specifically bans methods named build* or create*. However, methods named build or build* receive some special treatment because of the popular Builder Pattern. If the 'build' method is in a class named *Builder then it does not cause a violation. </p> <p>Builder methods are slightly different than factory methods. </p> <p>Example of violations: </p> <pre> class MyClass { // violation. Factory methods should be named make() def create() { } // violation. Factory methods should be named make() def createSomething() { } // violation. Builder method not in class named *Builder def build() { } // violation. Builder method not in class named *Builder def buildSomething() { } // this is OK because it is called make def make() { } // this is also OK def makeSomething() { } // OK, overriding a parent @Override build() { } } class WidgetBuilder { // OK, the class name ends in Builder def build() { } } </pre> ]]></description> <tag>bug</tag> <param> <key>regex</key> <description><![CDATA[Specifies the default regular expression used to validate the method name. It is required and cannot be null or empty. ]]></description> <defaultValue>(build.*\|create.*)</defaultValue> </param> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.naming.ClassNameSameAsFilenameRule</key> <severity>MINOR</severity> <name><![CDATA[Class Name Same As Filename]]></name> <internalKey><![CDATA[ClassNameSameAsFilename]]></internalKey> <description><![CDATA[<p>Reports files containing only one top level class / enum / interface which is named differently than the file. </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.22 --> <rule> <key>org.codenarc.rule.naming.PackageNameMatchesFilePathRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Package Name Matches File Path]]></name> <internalKey><![CDATA[PackageNameMatchesFilePath]]></internalKey> <description><![CDATA[<p> A package source file's path should match the package declaration. </p> ]]></description> <tag>bug</tag> <param> <key>groupId</key> <description><![CDATA[Specifies the common <group id> part of a package name, that will appear within all checked package names. It must also map to the file path for the correspondin source file. For instance, a <groupId> of <"org.sample"> means that for all classes that specify a package, that package name must include <"org.sample">, and the source file must exist under an "org/sample" directory. Then, a MyClass class in a org.sample.util package must be defined in a "MyClass.groovy" file within a <"org/sample/util"> directory. That directory can be the child of any arbitrary <root path>, e.g. "src/main/groovy". To find the sub-path relevant for the package the rule searches for the first appearance of <groupId> in the file path. It's <required> to configure this. If groupId is null or empty, this rule does nothing. ]]></description> </param> </rule> <!-- since 0.24 --> <rule> <key>org.codenarc.rule.naming.ClassNameSameAsSuperclassRule</key> <severity>MINOR</severity> <name><![CDATA[Class Name Same As Superclass]]></name> <internalKey><![CDATA[ClassNameSameAsSuperclass]]></internalKey> <description><![CDATA[<p>Checks for any class that has an identical name to its superclass, other than the package. This can be very confusing. </p> <p>Also see FindBugs NM_SAME_SIMPLE_NAME_AS_SUPERCLASS rule. </p> <p>Example of violations: </p> <pre> class MyClass extends other.MyClass // violation </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.24 --> <rule> <key>org.codenarc.rule.naming.InterfaceNameSameAsSuperInterfaceRule</key> <severity>MINOR</severity> <name><![CDATA[Interface Name Same As Super Interface]]></name> <internalKey><![CDATA[InterfaceNameSameAsSuperInterface]]></internalKey> <description><![CDATA[<p>Checks for any interface that has an identical name to its super-interface, other than the package. This can be very confusing. </p> <p>Example of violations: </p> <pre> interface MyInterface extends other.MyInterface { } // violation </pre> ]]></description> <tag>bug</tag> </rule> <!-- size rules --> <rule> <key>org.codenarc.rule.size.ClassSizeRule</key> <severity>MAJOR</severity> <name><![CDATA[Class Size]]></name> <internalKey><![CDATA[ClassSize]]></internalKey> <description><![CDATA[<p>Checks if the size of a class exceeds the number of lines specified by the <code>maxLines</code> property. </p> ]]></description> <tag>bug</tag> <param> <key>maxLines</key> <description><![CDATA[The maximum number of lines allowed in a class definition. ]]></description> <defaultValue>1000</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.size.CyclomaticComplexityRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Cyclomatic Complexity]]></name> <internalKey><![CDATA[CyclomaticComplexity]]></internalKey> <description><![CDATA[<p>Calculates the <Cyclomatic Complexity> for methods/classes and checks against configured threshold values. </p> <p>The <code>maxMethodComplexity</code> property holds the threshold value for the cyclomatic complexity value for each method. If this value is non-zero, a method with a cyclomatic complexity value greater than this value is considered a violation. </p> <p>The <code>maxClassAverageMethodComplexity</code> property holds the threshold value for the average cyclomatic complexity value for each class. If this value is non-zero, a class with an average cyclomatic complexity value greater than this value is considered a violation. </p> <p>This rule treats "closure fields" as methods. If a class field is initialized to a Closure (ClosureExpression), then that Closure is analyzed and checked just like a method. </p> The <cyclomatic complexity> value is calculated as follows: </p> <p><Start with a initial (default) value of one (1). Add one (1) for each occurrence of each of the following:> </p> ]]></description> <tag>bug</tag> <param> <key>ignoreMethodNames</key> <description><![CDATA[Specifies one or more (comma-separated) method names that that should not cause a rule violation. The names may optionally contain wildcards (*,?). Note that the ignored methods still contribute to the class complexity value. ]]></description> </param> <param> <key>maxClassAverageMethodComplexity</key> <description><![CDATA[The maximum average <cyclomatic complexity> value allowed for a class, calculated as the average complexity of its methods or "closure fields". If zero or <null>, then do not check average class-level complexity. ]]></description> <defaultValue>20</defaultValue> </param> <param> <key>maxClassComplexity</key> <description><![CDATA[The maximum total <cyclomatic complexity> value allowed for a class, calculated as the total complexity of its methods or "closure fields". If zero or <null>, then do not check total class-level complexity. ]]></description> <defaultValue>0</defaultValue> </param> <param> <key>maxMethodComplexity</key> <description><![CDATA[The maximum <cyclomatic complexity> value allowed for a single method (or "closure field"). If zero or <null>, then do not check method-level complexity. ]]></description> <defaultValue>20</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.size.MethodCountRule</key> <severity>MINOR</severity> <name><![CDATA[Method Count]]></name> <internalKey><![CDATA[MethodCount]]></internalKey> <description><![CDATA[<p>Checks if the number of methods within a class exceeds the number of lines specified by the <code>maxMethod</code> property. </p> <p>A class with too many methods is probably a good suspect for refactoring, in order to reduce its complexity and find a way to have more fine grained objects. </p> ]]></description> <tag>bug</tag> <param> <key>maxMethods</key> <description><![CDATA[The maximum number of methods allowed in a class definition. ]]></description> <defaultValue>30</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.size.MethodSizeRule.fixed</key> <severity>MAJOR</severity> <name><![CDATA[Method Size]]></name> <internalKey><![CDATA[MethodSize]]></internalKey> <description><![CDATA[<p>Checks if the size of a method exceeds the number of lines specified by the <code>maxLines</code> property. </p> <p>Known Limitations: </p> ]]></description> <tag>bug</tag> <param> <key>ignoreMethodNames</key> <description><![CDATA[Specifies one or more (comma-separated) method names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> <param> <key>maxLines</key> <description><![CDATA[The maximum number of lines allowed in a method definition. ]]></description> <defaultValue>100</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.size.NestedBlockDepthRule</key> <severity>MINOR</severity> <name><![CDATA[Nested Block Depth]]></name> <internalKey><![CDATA[NestedBlockDepth]]></internalKey> <description><![CDATA[<p>Checks for blocks or closures nested more deeply than a configured maximum number. Blocks include <code>if</code>, <code>for</code>, <code>while</code>, <code>switch</code>, <code>try</code>, <code>catch</code>, <code>finally</code> and <code>synchronized</code> blocks/statements, as well as closures. </p> <p>Methods calls, constructor calls, and property access through Builder objects are ignore. For instance, this code does not cause a violation: </p> <pre> myBuilder.root { foo { bar { baz { quix { qux { quaxz { } } } } } } } </pre> ]]></description> <tag>bug</tag> <param> <key>ignoreRegex</key> <description><![CDATA[Determines what is a builder call. For instance, closures nested on a method named createBuilder, a property named myBuilder, or a constructor call to object MyBuilder() do not produce violations. ]]></description> <defaultValue>.*(b|B)uilder</defaultValue> </param> <param> <key>maxNestedBlockDepth</key> <description><![CDATA[The maximum number of nesting levels. A block or closure nested deeper than that number of levels is considered a violation. ]]></description> <defaultValue>5</defaultValue> </param> </rule> <!-- since 0.17 --> <rule> <key>org.codenarc.rule.size.CrapMetricRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Crap Metric]]></name> <internalKey><![CDATA[CrapMetric]]></internalKey> <description><![CDATA[<p>Calculates the <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=210575">C.R.A.P.</a> (Change Risk Anti-Patterns) metric score for methods/classes and checks against configured threshold values. </p> <p>The <CRAP> metric score is based on the <cyclomatic complexity> and test coverage for individual methods. A method with a <CRAP> value greater than the <code>maxMethodCrapScore</code> property causes a violation. Likewise, a class that has an (average method) <CRAP> value greater than the <code>maxClassAverageMethodCrapScore</code> property causes a violation. </p> <p><code>NOTE:</code> This rule requires the <code>GMetrics</code>[3] jar, version 0.5 (or later), on the classpath, as well as a <code>Cobertura</code>[4]-[6] XML coverage file. If either of these prerequisites is not available, this rule logs a warning messages and exits (i.e., does nothing). </p> <p>The <code>maxMethodCrapScore</code> property holds the threshold value for the CRAP value for each method. If this value is non-zero, a method with a cyclomatic complexity value greater than this value is considered a violation. </p> <p>The <code>maxClassAverageMethodCrapScore</code> property holds the threshold value for the average CRAP value for each class. If this value is non-zero, a class with an average cyclomatic complexity value greater than this value is considered a violation. </p> <p>NOTE: This rule does NOT treat <closure fields> as methods (unlike some of the other size/complexity rules). </p> ]]></description> <tag>bug</tag> <param> <key>coberturaXmlFile</key> <description><![CDATA[The path to the Cobertura XML coverage file for the Groovy code By default, the path is relative to the classpath. But the path may be optionally prefixed by any of the valid java.net.URL prefixes, such as "file:" (to load from a relative or absolute path on the filesystem), or "http:". This property is REQUIRED. ]]></description> </param> <param> <key>ignoreMethodNames</key> <description><![CDATA[Specifies one or more (comma-separated) method names that that should not cause a rule violation. The names may optionally contain wildcards (*,?). Note that the ignored methods still contribute to the class complexity value. ]]></description> </param> <param> <key>maxClassAverageMethodCrapScore</key> <description><![CDATA[The maximum <CRAP> average metric value allowed for a class, calculated as the average CRAP value of its methods. If zero or <null>, then do not check the average class-level CRAP value. ]]></description> <defaultValue>30</defaultValue> </param> <param> <key>maxClassCrapScore</key> <description><![CDATA[The maximum total <CRAP> metric value allowed for a class, calculated as the total CRAP value of its methods. If zero or <null>, then do not check class-level CRAP value. ]]></description> <defaultValue>0</defaultValue> </param> <param> <key>maxMethodCrapScore</key> <description><![CDATA[The maximum <CRAP> metric value allowed for a single method. If zero or <null>, then do not check method-level complexity. ]]></description> <defaultValue>30</defaultValue> </param> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.size.AbcMetricRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Abc Metric]]></name> <internalKey><![CDATA[AbcMetric]]></internalKey> <description><![CDATA[<p>Calculates the <ABC> size metric for methods/classes and checks against configured threshold values. </p> <p>The <code>maxMethodAbcScore</code> property holds the threshold value for the ABC score for each method. If this value is non-zero, a method with an ABC score greater than this value is considered a violation. The value does not have to be an integer (e.g., 1.7 is allowed). </p> <p>The <code>maxClassAverageMethodAbcScore</code> property holds the threshold value for the average ABC score for each class. If this value is non-zero, a class with an average ABC score value greater than this value is considered a violation. The value does not have to be an integer. </p> <p>The <code>maxClassAbcScore</code> property holds the threshold value for the total ABC score value for each class. If this value is non-zero, a class with a total ABC score greater than this value is considered a violation. The value does not have to be an integer. </p> <p>This rule treats "closure fields" as methods. If a class field is initialized to a Closure (ClosureExpression), then that Closure is analyzed and checked just like a method. </p> The <ABC> score is calculated as follows: The <ABC> metric measures size by counting the number of Assignments (A), Branches (B) and Conditions (C) and assigns a single numerical score calculated as: </p> <p><code> |ABC| = sqrt((A*A)+(B*B)+(C*C)) </code> </p> <p>The <ABC Metric> calculation rules for Groovy: </p> ]]></description> <tag>bug</tag> <param> <key>ignoreMethodNames</key> <description><![CDATA[Specifies one or more (comma-separated) method names that that should not cause a rule violation. The names may optionally contain wildcards (*,?). Note that the ignored methods still contribute to the class complexity value. ]]></description> </param> <param> <key>maxClassAbcScore</key> <description><![CDATA[The maximum <ABC> score allowed for a class, calculated as the total ABC score of its methods or "closure fields". If zero or <null>, then do not check class-level scores. ]]></description> <defaultValue>0</defaultValue> </param> <param> <key>maxClassAverageMethodAbcScore</key> <description><![CDATA[The maximum average <ABC> score allowed for a class, calculated as the average score of its methods or "closure fields". If zero or <null>, then do not check class-level average scores. ]]></description> <defaultValue>60</defaultValue> </param> <param> <key>maxMethodAbcScore</key> <description><![CDATA[The maximum <ABC> score allowed for a single method (or "closure field"). If zero or <null>, then do not check method-level scores. ]]></description> <defaultValue>60</defaultValue> </param> </rule> <!-- since 0.23 --> <rule> <key>org.codenarc.rule.size.ParameterCountRule</key> <severity>MINOR</severity> <name><![CDATA[Parameter Count]]></name> <internalKey><![CDATA[ParameterCount]]></internalKey> <description><![CDATA[<p>Checks if the number of parameters in method/constructor exceeds the number of parameters specified by the maxParameters property. </p> <p>Example of violations: </p> <pre> void someMethod(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6) { // violation } class SampleClass { SampleClass(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7) { // violation } } </pre> ]]></description> <tag>bug</tag> <param> <key>maxParameters</key> <description><![CDATA[The maximum number of parameters in method/constructor ]]></description> <defaultValue>5</defaultValue> </param> </rule> <!-- unnecessary rules --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryBooleanExpressionRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Boolean Expression]]></name> <internalKey><![CDATA[UnnecessaryBooleanExpression]]></internalKey> <description><![CDATA[<p>Checks for unnecessary boolean expressions, including ANDing (&&) or ORing (||) with <code>true</code>, <code>false</code>, <code>null</code>, or a Map/List/String/Number literal. </p> <p>This rule also checks for negation (!) of <code>true</code>, <code>false</code>, <code>null</code>, or a Map/List/String/Number literal. </p> <p>Examples of violations include: </p> <pre> result = value && true // AND or OR with boolean constants if (false || value) { .. } return value && Boolean.FALSE result = null && value // AND or OR with null result = value && "abc" // AND or OR with String literal result = value && 123 // AND or OR with Number literal result = 678.123 || true result = value && [x, y] // AND or OR with List literal result = [a:123] && value // AND or OR with Map literal result = !true // Negation of boolean constants result = !false result = !Boolean.TRUE result = !null // Negation of null result = !"abc" // Negation of String literal result = ![a:123] // Negation of Map literal result = ![a,b] // Negation of List literal </pre> ]]></description> <tag>clumsy</tag> </rule> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryIfStatementRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary If Statement]]></name> <internalKey><![CDATA[UnnecessaryIfStatement]]></internalKey> <description><![CDATA[<p>Checks for unnecessary <code>if</code> statements. The entire <code>if</code> statement, or at least the <if> or <else> block, are considered unnecessary for the four scenarios described below. </p> <p>(1) When the <if> and <else> blocks contain only an explicit return of <code>true</code> and <code>false</code> constants. These cases can be replaced by a simple <return> statement. Examples of violations include: </p> <pre> if (someExpression) // can be replaced by: return someExpression return true else return false if (someExpression) { // can be replaced by: return !someExpression return false } else { return true } if (someExpression) { // can be replaced by: return someExpression return Boolean.TRUE } else { return Boolean.FALSE } </pre> <pre> def myMethod() { doSomething() if (someExpression) true else false } </pre> <pre> def myMethod() { doSomething() if (expression1) { return true } return false } </pre> <pre> def myMethod() { if (someExpression) { 123 } doSomething() } </pre> ]]></description> <tag>clumsy</tag> </rule> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryTernaryExpressionRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Ternary Expression]]></name> <internalKey><![CDATA[UnnecessaryTernaryExpression]]></internalKey> <description><![CDATA[<p>Checks for ternary expressions where the conditional expression always evaluates to a boolean and the <true> and <false> expressions are merely returning <code>true</code> and <code>false</code> constants. These cases can be replaced by a simple boolean expression. Examples of violations include: </p> <pre> x==99 ? true : false // can be replaced by: x==99 x && y ? true : false // can be replaced by: x && y x||y ? false : true // can be replaced by: !(x||y) x >= 1 ? true: false // can be replaced by: x >= 1 x < 99 ? Boolean.TRUE : Boolean.FALSE // can be replaced by: x < 99 !x ? true : false // can be replaced by: !x </pre> <pre> x ? '123' : '123' // can be replaced by: '123' x ? null : null // can be replaced by: null x ? 23 : 23 // can be replaced by: 23 x ? MAX_VALUE : MAX_VALUE // can be replaced by: MAX_VALUE ready ? minValue : minValue // can be replaced by: minValue </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryBigDecimalInstantiationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Big Decimal Instantiation]]></name> <internalKey><![CDATA[UnnecessaryBigDecimalInstantiation]]></internalKey> <description><![CDATA[<p>It is unnecessary to instantiate <code>BigDecimal</code> objects. Instead just use the decimal literal or the 'G' identifier to force the type, such as <code>123.45</code> or <code>123.45G</code>. </p> <p>This rule does not produce violations when the parameter evaluates to an integer/long, e.g. <code>new BigDecimal(42)</code>, <code>new BigDecimal(42L)</code> or <code>new BigDecimal("42")</code>, because using the "G" suffix on an integer value produces a <code>BigInteger</code>, rather than a <code>BigDecimal</code>, e.g. <code>45G</code>. So that means there is no way to produce a <code>BigDecimal</code> with exactly that value using a literal. </p> <p>This rule also does not produce violations when the parameter is a double, e.g. <code>new BigDecimal(12.3)</code>. That scenario is covered by the <a href="http://codenarc.sourceforge.net/codenarc-rules-basic.html#BigDecimalInstantiation">BigDecimalInstantiation</a> rule, because that produces an unpredictable (double) value (and so it is <unsafe>, rather than <unnecessary>). </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryBigIntegerInstantiationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Big Integer Instantiation]]></name> <internalKey><![CDATA[UnnecessaryBigIntegerInstantiation]]></internalKey> <description><![CDATA[<p>It is unnecessary to instantiate <code>BigInteger</code> objects. Instead just use the literal with the 'G' identifier to force the type, such as <code>8G</code> or <code>42G</code>. </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryBooleanInstantiationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Boolean Instantiation]]></name> <internalKey><![CDATA[UnnecessaryBooleanInstantiation]]></internalKey> <description><![CDATA[<p>Checks for direct call to a <code>Boolean</code> constructor. Use <code>Boolean.valueOf()</code> or the <code>Boolean.TRUE</code> and <code>Boolean.FALSE</code> constants instead of calling the <code>Boolean()</code> constructor directly. </p> <p>Also checks for <code>Boolean.valueOf(true)</code> or <code>Boolean.valueOf(false)</code>. Use the <code>Boolean.TRUE</code> or <code>Boolean.FALSE</code> constants instead. </p> <p>Here is an example of code that produces a violation: </p> <pre> def b1 = new Boolean(true) // violation def b2 = new java.lang.Boolean(false) // violation def b3 = Boolean.valueOf(true) // violation def b4 = Boolean.valueOf(false) // violation </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryCallForLastElementRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Call For Last Element]]></name> <internalKey><![CDATA[UnnecessaryCallForLastElement]]></internalKey> <description><![CDATA[<p>This rule checks for excessively verbose methods of accessing the last element of an array or list. For instance, it is possible to access the last element of an array by performing <code>array[array.length - 1]</code>, in Groovy it is simpler to either call <code>array.last()</code> or <code>array[-1]</code>. The same is true for lists. This violation is triggered whenever a <code>get</code>, <code>getAt</code>, or array-style access is used with an object size check. </p> <p>Code like this all cause violations. </p> <pre> def x = [0, 1, 2] def a = x.get(x.size() -1) def b = x.get(x.length -1) def c = x.getAt(x.size() -1) def d = x.getAt(x.length -1) def f = x[(x.size() -1] def d = x[(x.length -1] </pre> <pre> def x = [0, 1, 2] def a = x.last() def b = x[-1] def c = x.getAt(-1) def d = x.get(z.size() -1) // different objects def e = x.get(z.length -1) // different objects def f = x.getAt(z.size() -1) // different objects </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryCatchBlockRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Catch Block]]></name> <internalKey><![CDATA[UnnecessaryCatchBlock]]></internalKey> <description><![CDATA[<p>Violations are triggered when a <catch> block does nothing but throw the original exception. In this scenario there is usually no need for a <catch> block, just let the exception be thrown from the original code. This condition frequently occurs when catching an exception for debugging purposes but then forgetting to take the <code>catch</code> statement out. </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryCollectCallRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Collect Call]]></name> <internalKey><![CDATA[UnnecessaryCollectCall]]></internalKey> <description><![CDATA[<p>Some method calls to <code>Object.collect(Closure)</code> can be replaced with the spread operator. For instance, <code>list.collect { it.multiply(2) }</code> can be replaced by <code>list*.multiply(2)</code>. </p> <p>Examples of violations include: </p> <pre> assert [1, 2, 3].collect { it.multiply(2) } assert [1, 2, 3].collect { x -> x.multiply(2) } ["1", "2", "3"].collect { it.bytes } </pre> <pre> [1, 2, 3].collect { it * it } // OK, closure parameter is referenced twice [1, 2, 3].mapMethod { it.multiply(5) } // OK, method call is not collect [1, 2, 3].collect(5) // OK, collect parameter is not a closure // OK, the closure is not a simple one line statement [1, 2, 3].collect { println it; it.multiply(5) } // OK, closure has too many arguments [1, 2, 3].collect { a, b -> a.multiply(b) } // OK, closure statement references parameter multiple times [1, 2, 3].collect { it.multiply(it) } // OK, it is referenced several times in the closure [1, 2, 3].collect { it.multiply(2).multiply(it) } ["1", "2", "3"].collect { it.bytes.foo(it) } // OK, chained methods are too complex to analyze at this point [1, 2, 3].collect { it.multiply(2).multiply(4) } // in general the above examples can be rewritten like this: [1, 2, 3]*.multiply(2) ["1", "2", "3"]*.bytes </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryCollectionCallRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Collection Call]]></name> <internalKey><![CDATA[UnnecessaryCollectionCall]]></internalKey> <description><![CDATA[<p>Checks for useless calls to collections. For any collection <code>c</code>, calling <code>c.containsAll(c)</code> should always be <code>true</code>, and <code>c.retainAll(c)</code> should have no effect. </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryConstructorRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Constructor]]></name> <internalKey><![CDATA[UnnecessaryConstructor]]></internalKey> <description><![CDATA[<p>This rule detects when a constructor is not necessary; i.e., when there's only one constructor, it's <code>public</code>, has an empty body, and takes no arguments, or else contains only a single call to <code>super()</code>. </p> <p>Example of violations: </p> <pre> class MyClass { public MyClass() { // violation; constructor is not necessary } } class MyClass2 extends OtherClass { MyClass2() { // violation; constructor is not necessary super() } } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryDoubleInstantiationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Double Instantiation]]></name> <internalKey><![CDATA[UnnecessaryDoubleInstantiation]]></internalKey> <description><![CDATA[<p>It is unnecessary to instantiate <code>Double</code> objects. Instead just use the double literal with 'D' identifier to force the type, such as <code>123.45d</code> or <code>0.42d</code>. </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryFloatInstantiationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Float Instantiation]]></name> <internalKey><![CDATA[UnnecessaryFloatInstantiation]]></internalKey> <description><![CDATA[<p>It is unnecessary to instantiate <code>Float</code> objects. Instead just use the float literal with the 'F' identifier to force the type, such as <code>123.45F</code> or <code>0.42f</code>. </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryGetterRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Getter]]></name> <internalKey><![CDATA[UnnecessaryGetter]]></internalKey> <description><![CDATA[<p>Checks for explicit calls to getter/accessor methods which can, for the most part, be replaced by property access. A getter is defined as a method call that matches <code>get[A-Z]</code> but not <code>getClass()</code> or <code>get[A-Z][A-Z]</code> such as <code>getURL()</code>. Getters do not take method arguments. </p> <p>These bits of code produce violations: </p> <pre> x.getProperty() x.getFirst() x.getFirstName() x.getA() </pre> <pre> x.property x.first x.firstName x.a x.getURL() x.getClass() x.getProperty('key') </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryGStringRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary G String]]></name> <internalKey><![CDATA[UnnecessaryGString]]></internalKey> <description><![CDATA[<p>String objects should be created with single quotes, and GString objects created with double quotes. Creating normal String objects with double quotes is confusing to readers. </p> <p>Example of violations: </p> <pre> def a = "I am a string" // violation // violation def b = """ I am a string """ def c = "I am a ' string" // OK def d = """I am a ' string""" // OK def e = """I am a ' string""" // OK def f = "I am a \$ string" // OK // OK def g = """ I am a \$ string """ // OK def h = """ I am a $string """ def i = 'i am a string' def j = '''i am a string ''' </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryInstantiationToGetClassRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Instantiation To Get Class]]></name> <internalKey><![CDATA[UnnecessaryInstantiationToGetClass]]></internalKey> <description><![CDATA[<p>Avoid instantiating an object just to call getClass() on it; use the .class public member instead. </p> <pre> public class Foo { // Replace this Class c = new String().getClass(); // with this: Class c = String.class; } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryIntegerInstantiationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Integer Instantiation]]></name> <internalKey><![CDATA[UnnecessaryIntegerInstantiation]]></internalKey> <description><![CDATA[<p>It is unnecessary to instantiate <code>Integer</code> objects. Instead just use the literal with the 'I' identifier to force the type, such as <code>8I</code> or <code>42i</code>. </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryLongInstantiationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Long Instantiation]]></name> <internalKey><![CDATA[UnnecessaryLongInstantiation]]></internalKey> <description><![CDATA[<p>It is unnecessary to instantiate <code>Long</code> objects. Instead just use the literal with the 'L' identifier to force the type, such as <code>8L</code> or <code>42L</code>. </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryObjectReferencesRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Object References]]></name> <internalKey><![CDATA[UnnecessaryObjectReferences]]></internalKey> <description><![CDATA[<p>Violations are triggered when an excessive set of consecutive statements all reference the same variable. This can be made more readable by using a <code>with</code> or <code>identity</code> block. By default, 5 references are allowed. You can override this property using the <code>maxReferencesAllowed</code> property on the rule. </p> <p>These two bits of code produce violations: </p> <pre> def p1 = new Person() p1.firstName = 'Hamlet' p1.lastName = "D'Arcy" p1.employer = 'Canoo' p1.street = 'Kirschgaraten 5' p1.city = 'Basel' p1.zipCode = '4051' def p2 = new Person() p2.setFirstName('Hamlet') p2.setLastName("D'Arcy") p2.setEmployer('Canoo') p2.setStreet('Kirschgaraten 5') p2.setCity('Basel') p2.setZipCode('4051') </pre> <pre> def p1 = new Person().with { firstName = 'Hamlet' lastName = "D'Arcy" employer = 'Canoo' street = 'Kirschgaraten 5' city = 'Basel' zipCode = '4051' } def p2 = new Person().identity { firstName = 'Hamlet' lastName = "D'Arcy" employer = 'Canoo' street = 'Kirschgaraten 5' city = 'Basel' zipCode = '4051' } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryNullCheckRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Null Check]]></name> <internalKey><![CDATA[UnnecessaryNullCheck]]></internalKey> <description><![CDATA[<p>Groovy contains the safe dereference operator. It can be used in boolean conditional statements to safely replace explicit <code>x == null</code> tests. Also, testing the 'this' or 'super' reference for null equality is pointless and can be removed. </p> <p>Examples of violations: </p> <pre> if (obj != null && obj.method()) { } if (obj != null && obj.prop) { } // this is pointless and won't avoid NullPointerException if (obj.method() && obj != null ) { } if (this == null) { } if (null == this) { } if (this != null) { } if (null != this) { } if (super == null) { } if (null == super) { } if (super != null) { } if (null != super) { } </pre> <pre> // null check it OK if (obj != null) { } // null safe dereference in if is OK if (obj?.method()) { } // null safe dereference in ternary is OK (obj?.prop && obj?.prop2) ? x : y // obj is reused in a parameter list, so OK if (obj != null && obj.method() && isValid(obj)) { } // rule is not so complex yet... (obj != null && obj.prop && obj.method()) ? x : y </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryNullCheckBeforeInstanceOfRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Null Check Before Instance Of]]></name> <internalKey><![CDATA[UnnecessaryNullCheckBeforeInstanceOf]]></internalKey> <description><![CDATA[<p>There is no need to check for null before an instanceof; the instanceof keyword returns false when given a null argument. </p> <p>Example: </p> <pre> if (x != null && x instanceof MyClass) { // should drop the "x != null" check } if (x instanceof MyClass && x != null) { // should drop the "x != null" check } // should drop the "x != null" check (x != null && x instanceof MyClass) ? foo : bar if (x != null && x instanceof MyClass && x.isValid()) { // this is OK and causes no violation because the x.isValid() requires a non null reference } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryOverridingMethodRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Overriding Method]]></name> <internalKey><![CDATA[UnnecessaryOverridingMethod]]></internalKey> <description><![CDATA[<p>Checks for an overriding method that merely calls the same method defined in a superclass. Remove it. </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryReturnKeywordRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Return Keyword]]></name> <internalKey><![CDATA[UnnecessaryReturnKeyword]]></internalKey> <description><![CDATA[<p>In Groovy, the <code>return</code> keyword is often optional. If a statement is the last line in a method or closure then you do not need to have the <code>return</code> keyword. </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryStringInstantiationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary String Instantiation]]></name> <internalKey><![CDATA[UnnecessaryStringInstantiation]]></internalKey> <description><![CDATA[<p>Checks for direct call to the <code>String</code> constructor that accepts a <code>String</code> literal. In almost all cases, this is unnecessary. Use a <code>String</code> literal (e.g., "...") instead of calling the corresponding <code>String</code> constructor (<code>new String("..")</code>) directly. </p> <p>Here is an example of code that produces a violation: </p> <pre> def s = new String('abc') </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.unnecessary.AddEmptyStringRule</key> <severity>MINOR</severity> <name><![CDATA[Add Empty String]]></name> <internalKey><![CDATA[AddEmptyString]]></internalKey> <description><![CDATA[<p>Finds empty string literals which are being added. This is an inefficient way to convert any type to a String. </p> <p>Examples: </p> <pre> // do not add empty strings to things def a = '' + 123 def b = method('' + property) // these examples are OK and do not trigger violations def c = 456.toString() def d = property?.toString() ?: "" </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.unnecessary.ConsecutiveLiteralAppendsRule</key> <severity>MINOR</severity> <name><![CDATA[Consecutive Literal Appends]]></name> <internalKey><![CDATA[ConsecutiveLiteralAppends]]></internalKey> <description><![CDATA[<p>Violations occur when method calls to append(Object) are chained together with literals as parameters. The chained calls can be joined into one invocation. </p> <p>Example of violations: </p> <pre> writer.append('foo').append('bar') // strings can be joined writer.append('foo').append(5) // string and number can be joined writer.append('Hello').append("$World") // GString can be joined </pre> <pre> // usage not chained invocation writer.append('Hello') writer.append('World') writer.append(null).append(5) // nulls cannot be joined writer.append().append('Hello') // no arg append is unknown writer.append('a', 'b').append('Hello') // two arg append is unknown </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.unnecessary.ConsecutiveStringConcatenationRule</key> <severity>MAJOR</severity> <name><![CDATA[Consecutive String Concatenation]]></name> <internalKey><![CDATA[ConsecutiveStringConcatenation]]></internalKey> <description><![CDATA[<p>Catches concatenation of two string literals on the same line. These can safely by joined. In Java, the Java compiler will join two String literals together and place them in the Constant Pool. However, Groovy will not because the plus() method may override the + operator. </p> <p>Examples: </p> <pre> // Violations def a = 'Hello' + 'World' // should be 'HelloWorld' def b = "$Hello" + 'World' // should be "${Hello}World" def c = 'Hello' + "$World" // should be "Hello${World}" def d = 'Hello' + 5 // should be 'Hello5' def e = 'Hello' + ''' world // should be joined ''' def f = '''Hello ''' + 'world' // should be joined // Not Violations def g = 'Hello' + // OK because of line break 'World' def h = 'Hello' + null // OK because not a string def i = 'Hello' + method() // OK because not a string def j = 'Hello' - "$World" // OK because not + </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryCallToSubstringRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Call To Substring]]></name> <internalKey><![CDATA[UnnecessaryCallToSubstring]]></internalKey> <description><![CDATA[<p>Calling String.substring(0) always returns the original string. This code is meaningless. </p> <p>Examples: </p> <pre> string.substring(0) // violation method().substring(0) // violation prop.substring(1) // OK, not constant 0 prop.substring(0, 1) // OK, end is specified </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryDefInMethodDeclarationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Def In Method Declaration]]></name> <internalKey><![CDATA[UnnecessaryDefInMethodDeclaration]]></internalKey> <description><![CDATA[<p>If a method has a visibility modifier or a type declaration, then the def keyword is unneeded. For instance 'def private method() {}' is redundant and can be simplified to 'private method() {}'. </p> <p>Examples of violations: </p> <pre> // def and private is redundant def private method1() { return 4 } // def and protected is redundant def protected method2() { return 4 } // def and public is redundant def public method3() { return 4 } // def and static is redundant def static method4() { return 4 } // def and type is redundant def Object method5() { return 4 } class MyClass { def MyClass() {} // def is redundant } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryModOneRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Mod One]]></name> <internalKey><![CDATA[UnnecessaryModOne]]></internalKey> <description><![CDATA[<p>Any expression mod 1 (exp % 1) is guaranteed to always return zero. This code is probably an error, and should be either (exp & 1) or (exp % 2). </p> <p>Examples: </p> <pre> if (exp % 1) {} // violation if (method() % 1) {} // violation if (exp & 1) {} // ok if (exp % 2) {} // ok </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryPublicModifierRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Public Modifier]]></name> <internalKey><![CDATA[UnnecessaryPublicModifier]]></internalKey> <description><![CDATA[<p>The 'public' modifier is not required on methods, constructors or classes. </p> <p>Example of violations: </p> <pre> // violation on class public class MyClass { // violation on constructor public MyClass() {} // violation on method public void myMethod() {} } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessarySelfAssignmentRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Self Assignment]]></name> <internalKey><![CDATA[UnnecessarySelfAssignment]]></internalKey> <description><![CDATA[<p>Method contains a pointless self-assignment to a variable or property. Either the code is pointless or the equals()/get() method has been overridden to have a side effect, which is a terrible way to code getters and violates the contract of equals(). </p> <p>Examples: </p> <pre> x = x // violation def method(y) { y = y // violation } a.b.c = a.b.c // violation x = y // acceptable a.b = a.zz // acceptable a.b = a().b // acceptable </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessarySemicolonRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Semicolon]]></name> <internalKey><![CDATA[UnnecessarySemicolon]]></internalKey> <description><![CDATA[<p>Semicolons as line terminators are not required in Groovy: remove them. Do not use a semicolon as a replacement for empty braces on for and while loops; this is a confusing practice. </p> <p>The rule contains a String property called 'excludePattern'. Any source code line matching this pattern will not trigger a violation. The default value is '\\s?\\*.*|/\\*.*|.*//.*|.*\\*/.*' This is to filter out comments. Any source line that even looks like it is a comment is ignored. </p> <p>\s?\*.* == whitespace plus star character plus anything /\*.* == any line that contains the /* sequence .*//.* == any line that contains the // sequence .*\*/.* == any line that contains the */ sequence </p> <p>Example of violations: </p> <pre> package my.company.server; // violation import java.lang.String; // violation println(value) ; // violation for (def x : list); // violation // this code is OK println(value); println (otherValue) </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryTransientModifierRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Transient Modifier]]></name> <internalKey><![CDATA[UnnecessaryTransientModifier]]></internalKey> <description><![CDATA[<p>The field is marked as transient, but the class isn't Serializable, so marking it as transient has no effect. This may be leftover marking from a previous version of the code in which the class was transient, or it may indicate a misunderstanding of how serialization works. </p> <p>Some Java frameworks change the semantics of the transient keyword. For instance, when using Terracotta the transient keyword may have slightly different semantics. You may need to turn this rule off depending on which Java frameworks are in use. </p> Examples: </p> <pre> class MyClass { // class not serializable, violation occurs transient String property } class MySerializableClass implements Serializable { // OK, class is serializable transient String property } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryFinalOnPrivateMethodRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Final On Private Method]]></name> <internalKey><![CDATA[UnnecessaryFinalOnPrivateMethod]]></internalKey> <description><![CDATA[<p>A private method is marked final. Private methods cannot be overridden, so marking it final is unnecessary. </p> <p>Example of violations: </p> <pre> private final method() {} </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryElseStatementRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Else Statement]]></name> <internalKey><![CDATA[UnnecessaryElseStatement]]></internalKey> <description><![CDATA[<p>When an <code>if</code> statement block ends with a <code>return</code> statement, then the <code>else</code> is unnecessary. The logic in the <code>else</code> branch can be run without being in a new scope. </p> <p>Example of violations: </p> <pre> if(value){ println 'Executing if logic...' return true } else { println 'Executing else logic...' } // can be replaced by: if(value){ println 'Executing if logic...' return true } println 'Executing else logic...' </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryParenthesesForMethodCallWithClosureRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Parentheses For Method Call With Closure]]></name> <internalKey><![CDATA[UnnecessaryParenthesesForMethodCallWithClosure]]></internalKey> <description><![CDATA[<p>If a method is called and the only parameter to that method is an inline closure then the parentheses of the method call can be omitted. </p> <p>Example of violations: </p> <pre> [1,2,3].each() { println it } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryPackageReferenceRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Package Reference]]></name> <internalKey><![CDATA[UnnecessaryPackageReference]]></internalKey> <description><![CDATA[<p>Checks for explicit package reference for classes that Groovy imports by default, such as <code>java.lang.String</code>, <code>java.util.Map</code> and <code>groovy.lang.Closure</code>, as well as classes that were explicitly imported. </p> <p>You do not need to specify the package for any classes from <java.lang>, <java.util>, <java.io>, <java.net>, <groovy.lang> and <groovy.util>, as well as the classes <java.math.BigDecimal> and <java.math.BigInteger>. </p> <p>Examples of violations include: </p> <pre> // Field types class MyClass { java.math.BigDecimal amount = 42.10 // violation } // Within expressions if (value.class == java.math.BigInteger) { } // violation println "isClosure=${v instanceof groovy.lang.Closure}" // violation def p = java.lang.Runtime.availableProcessors() // violation // Constructor calls def url = new java.net.URL('http://[email protected]') // violation // Variable types void doSomething() { java.math.BigInteger maxValue = 0 // violation java.net.URI uri // violation } // Method return types java.io.Reader getReader() { } // violation groovy.util.AntBuilder getAntBuilder() { } // violation // Method parameter types void writeCount(java.io.Writer writer, int count) { } // violation void init(String name, groovy.lang.Binding binding) { } // violation // Closure parameter types def writeCount = { java.io.Writer writer, int count -> } // violation // Extends and implements class MyHashMap extends java.util.HashMap { } // violation class MyList implements java.util.List { } // violation // Explicitly imported classes import javax.servlet.http.Cookie import javax.sql.DataSource class MyClass { void doStuff(javax.servlet.http.Cookie cookie) { // violation def dataSource = [:] as javax.sql.DataSource // violation } } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryDefInVariableDeclarationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Def In Variable Declaration]]></name> <internalKey><![CDATA[UnnecessaryDefInVariableDeclaration]]></internalKey> <description><![CDATA[<p>If a variable has a visibility modifier or a type declaration, then the def keyword is unneeded. For instance 'def private n = 2' is redundant and can be simplified to 'private n = 2'. </p> <p>Examples of violations: </p> <pre> // def and private is redundant def private string1 = 'example' // def and protected is redundant def protected string2 = 'example' // def and public is redundant def public string3 = 'example' // def and static is redundant def static string4 = 'example' // def and final is redundant def final string5 = 'example' // def and a type is redundant def String string6 = 'example' </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryDotClassRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Dot Class]]></name> <internalKey><![CDATA[UnnecessaryDotClass]]></internalKey> <description><![CDATA[<p>To make a reference to a class, it is unnecessary to specify the '.class' identifier. For instance String.class can be shortened to String. </p> <p>Example of violations: </p> <pre> // The '.class' identifier is unnecessary, violation occurs def x = String.class // Ok, unnecessary '.class' identifier has been excluded def x = String </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryInstanceOfCheckRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Instance Of Check]]></name> <internalKey><![CDATA[UnnecessaryInstanceOfCheck]]></internalKey> <description><![CDATA[<p>This rule finds instanceof checks that cannot possibly evaluate to true. For instance, checking that <code>(!variable instanceof String)</code> will never be true because the result of a not expression is always a boolean. </p> <p>Example of violations: </p> <pre> if (!variable instanceof String) { ... } // always false def x = !variable instanceof String // always false if (!variable instanceof Boolean) { ... } // always true def x = !variable instanceof Boolean // always true // this code is OK if (!(variable instanceof String)) { ... } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessarySubstringRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Substring]]></name> <internalKey><![CDATA[UnnecessarySubstring]]></internalKey> <description><![CDATA[<p>This rule finds usages of <code>String.substring(int)</code> and <code>String.substring(int, int)</code> that can be replaced by use of the subscript operator. For instance, <code>var.substring(5)</code> can be replaced with <code>var[5..-1]</code>. </p> <p>Note that the String.substring(beginIndex,endIndex) method specifies a range of beginIndex..endIndex-1, while Groovy's String subscript specifies an inclusive range. So, <code>"123456".substring(1, 5)</code> is equivalent to <code>"123456"[1..4]</code>. </p> <p>Example of violations: </p> <pre> myVar.substring(5) // can use myVar[5..-1] instead myVar.substring(1, 5) // can use myVar[1..4] instead </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryDefInFieldDeclarationRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Def In Field Declaration]]></name> <internalKey><![CDATA[UnnecessaryDefInFieldDeclaration]]></internalKey> <description><![CDATA[<p>If a field has a visibility modifier or a type declaration, then the def keyword is unneeded. For instance, 'static def constraints = {}' is redundant and can be simplified to 'static constraints = {}. </p> <p>Example of violations: </p> <pre> class MyClass { // def is redundant static def constraints = { } // def and private is redundant def private field1 = { } // def and protected is redundant def protected field2 = { } // def and public is redundant def public field3 = { } // def and static is redundant def static field4 = { } // def and type is redundant def Object field5 = { } } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryCastRule</key> <severity>MINOR</severity> <name><![CDATA[Unnecessary Cast]]></name> <internalKey><![CDATA[UnnecessaryCast]]></internalKey> <description><![CDATA[<p>Checks for unnecessary cast operations. </p> <p>Example of violations: </p> <pre> int count = (int)123 // violation def longValue = (long)123456L // violation def bigDecimal = (BigDecimal)1234.56 // violation String name = (String) "Joe" // violation def list = (List)[1, 2, 3] // violation def map = (Map)[a:1] // violation </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessaryToStringRule</key> <severity>MINOR</severity> <name><![CDATA[Unnecessary To String]]></name> <internalKey><![CDATA[UnnecessaryToString]]></internalKey> <description><![CDATA[<p>Checks for unnecessary calls to <code>toString()</code>. This includes: </p> ]]></description> <tag>clumsy</tag> </rule> <!-- since 0.22 --> <rule> <key>org.codenarc.rule.unnecessary.UnnecessarySafeNavigationOperatorRule</key> <severity>MAJOR</severity> <name><![CDATA[Unnecessary Safe Navigation Operator]]></name> <internalKey><![CDATA[UnnecessarySafeNavigationOperator]]></internalKey> <description><![CDATA[<p> Check for the <safe navigation> operator (<code>?.</code>) applied to constants and literals, or <code>this</code> or <code>super</code>, or constructor calls, all of which can never be null. </p> <p>Example of violations: </p> <pre> def myMethod() { "abc"?.bytes // violation [1,2]?.getSize() // violation [abc:123]?.name // violation [:]?.toString() // violation 123?.class // violation 123.45?.getClass() // violation Boolean.FALSE?.class // violation Boolean.TRUE?.class // violation this?.class // violation super?.getClass() // violation new Long(100)?.class // violation } </pre> ]]></description> <tag>clumsy</tag> </rule> <!-- unused rules --> <rule> <key>org.codenarc.rule.unused.UnusedArrayRule</key> <severity>MINOR</severity> <name><![CDATA[Unused Array]]></name> <internalKey><![CDATA[UnusedArray]]></internalKey> <description><![CDATA[<p>Checks for array allocations that are not assigned or used, unless it is the last statement within a block (because it may be the intentional return value). Examples include: </p> <pre> int myMethod() { new String[3] // unused return -1 } String[] myMethod() { new String[3] // OK (last statement in block) } def closure = { doStuff() new Date[3] // unused doOtherStuff() } def closure = { new Date[3] } // OK (last statement in block) </pre> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.unused.UnusedObjectRule</key> <severity>MINOR</severity> <name><![CDATA[Unused Object]]></name> <internalKey><![CDATA[UnusedObject]]></internalKey> <description><![CDATA[<p>Checks for object allocations that are not assigned or used, unless it is the last statement within a block (because it may be the intentional return value). Examples include: </p> <p>By default, this rule does not analyze test files. This rule sets the default value of the <doNotApplyToFilesMatching> property to ignore file names ending in 'Test.groovy', 'Tests.groovy' or 'TestCase.groovy'. Invoking constructors without using the result is a common pattern in tests. </p> <pre> int myMethod() { new BigDecimal("23.45") // unused return -1 } BigDecimal myMethod() { new BigDecimal("23.45") // OK (last statement in block) } def closure = { doStuff() new Date() // unused doOtherStuff() } def closure = { new Date() } // OK (last statement in block) </pre> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.unused.UnusedPrivateFieldRule</key> <severity>MINOR</severity> <name><![CDATA[Unused Private Field]]></name> <internalKey><![CDATA[UnusedPrivateField]]></internalKey> <description><![CDATA[<p>Checks for private fields that are not referenced within the same class. Note that the <code>private</code> modifier is not currently "respected" by Groovy code (i.e., Groovy can access <code>private</code> members within other classes). By default, fields named <code>serialVersionUID</code> are ignored. The rule has a property named ignoreFieldNames, which can be set to ignore other field names as well. For instance, to ignore fields named 'fieldx', set the property to the 'fieldx, serialVersionUID' </p> <p>Known limitations: </p> ]]></description> <tag>bug</tag> <param> <key>ignoreFieldNames</key> <description><![CDATA[Specifies one or more (comma-separated) field names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> <defaultValue>serialVersionUID</defaultValue> </param> </rule> <rule> <key>org.codenarc.rule.unused.UnusedPrivateMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Unused Private Method]]></name> <internalKey><![CDATA[UnusedPrivateMethod]]></internalKey> <description><![CDATA[<p>Checks for private methods that are not referenced within the same class. Note that the <code>private</code> modifier is not currently "respected" by Groovy code (i.e., Groovy can access <code>private</code> members within other classes). </p> <p>Known limitations: </p> ]]></description> <tag>bug</tag> </rule> <rule> <key>org.codenarc.rule.unused.UnusedVariableRule.fixed</key> <severity>MINOR</severity> <name><![CDATA[Unused Variable]]></name> <internalKey><![CDATA[UnusedVariable]]></internalKey> <description><![CDATA[<p>Checks for variables that are never referenced. </p> <p>The rule has a property named ignoreVariableNames, which can be set to ignore some variable names. For instance, to ignore fields named 'unused', set the property to 'unused'. </p> <p>Known limitations: </p> ]]></description> <tag>bug</tag> <param> <key>ignoreVariableNames</key> <description><![CDATA[Specifies one or more (comma-separated) variable names that should be ignored (i.e., that should not cause a rule violation). The names may optionally contain wildcards (*,?). ]]></description> </param> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.unused.UnusedPrivateMethodParameterRule</key> <severity>MINOR</severity> <name><![CDATA[Unused Private Method Parameter]]></name> <internalKey><![CDATA[UnusedPrivateMethodParameter]]></internalKey> <description><![CDATA[<p>Checks for parameters to private methods that are not referenced within the method body. Note that the <code>private</code> modifier is not currently "respected" by Groovy code (i.e., Groovy can access <code>private</code> members within other classes). </p> <p>Known limitations: </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.unused.UnusedMethodParameterRule</key> <severity>MINOR</severity> <name><![CDATA[Unused Method Parameter]]></name> <internalKey><![CDATA[UnusedMethodParameter]]></internalKey> <description><![CDATA[<p>This rule finds instances of method parameters not being used. It does not analyze private methods (that is done by the UnusedPrivateMethodParameter rule) or methods marked @Override. </p> ]]></description> <tag>bug</tag> </rule> <!-- jdbc rules --> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.jdbc.DirectConnectionManagementRule</key> <severity>MINOR</severity> <name><![CDATA[Direct Connection Management]]></name> <internalKey><![CDATA[DirectConnectionManagement]]></internalKey> <description><![CDATA[<p>The J2EE standard requires that applications use the container's resource management facilities to obtain connections to resources. Every major web application container provides pooled database connection management as part of its resource management framework. Duplicating this functionality in an application is difficult and error prone, which is part of the reason it is forbidden under the J2EE standard. </p> <p>For more information see: <a>https://www.fortify.com/vulncat/en/vulncat/java/j2ee_badpractices_getconnection.html</a> </p> <p>Example of violations: </p> <pre> DriverManager.getConnection() java.sql.DriverManager.getConnection() </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.jdbc.JdbcConnectionReferenceRule</key> <severity>MINOR</severity> <name><![CDATA[Jdbc Connection Reference]]></name> <internalKey><![CDATA[JdbcConnectionReference]]></internalKey> <description><![CDATA[<p>Checks for direct use of <code>java.sql.Connection</code>, which is discouraged and almost never necessary in application code. </p> <p>For a more <Groovy> alternative, see <a>http://groovy.codehaus.org/Database+features</a> for information on the <code>Groovy Sql</code> abstraction layer for JDBC/SQL. </p> <p>Note: If a violation is triggered from an <code>import</code> statement, then you may get multiple violations per import if there are multiple classes in the source file. In that case, the imports are processed once per class. </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.jdbc.JdbcResultSetReferenceRule</key> <severity>MINOR</severity> <name><![CDATA[Jdbc Result Set Reference]]></name> <internalKey><![CDATA[JdbcResultSetReference]]></internalKey> <description><![CDATA[<p>Checks for direct use of <code>java.sql.ResultSet</code>, which is not necessary if using the Groovy <code>Sql</code> facility or an ORM framework such as <Hibernate>. </p> <p>See <a>http://groovy.codehaus.org/Database+features</a> for information on the <code>Groovy Sql</code> abstraction layer for JDBC/SQL. </p> <p>Note: If a violation is triggered from an <code>import</code> statement, then you may get multiple violations per import if there are multiple classes in the source file. In that case, the imports are processed once per class. </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.jdbc.JdbcStatementReferenceRule</key> <severity>MINOR</severity> <name><![CDATA[Jdbc Statement Reference]]></name> <internalKey><![CDATA[JdbcStatementReference]]></internalKey> <description><![CDATA[<p>Checks for direct use of <code>java.sql.Statement</code>, <code>java.sql.PreparedStatement</code>, or <code>java.sql.CallableStatement</code>, which is not necessary if using the Groovy <code>Sql</code> facility or an ORM framework such as <Hibernate>. </p> <p>See <a>http://groovy.codehaus.org/Database+features</a> for information on the <code>Groovy Sql</code> abstraction layer for JDBC/SQL. </p> <p>Note: If a violation is triggered from an <code>import</code> statement, then you may get multiple violations per import if there are multiple classes in the source file. In that case, the imports are processed once per class. </p> ]]></description> <tag>bug</tag> </rule> <!-- security rules --> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.security.NonFinalSubclassOfSensitiveInterfaceRule</key> <severity>MINOR</severity> <name><![CDATA[Non Final Subclass Of Sensitive Interface]]></name> <internalKey><![CDATA[NonFinalSubclassOfSensitiveInterface]]></internalKey> <description><![CDATA[<p>The permissions classes such as <code>java.security.Permission</code> and <code>java.security.BasicPermission</code> are designed to be extended. Classes that derive from these permissions classes, however, must prohibit extension. This prohibition ensures that malicious subclasses cannot change the properties of the derived class. Classes that implement sensitive interfaces such as <code>java.security.PrivilegedAction</code> and <code>java.security.PrivilegedActionException</code> must also be declared <code>final</code> for analogous reasons. </p> <p>For more information see: <a>https://www.securecoding.cert.org/confluence/display/java/SEC07-J.+Classes+that+derive+from+a+sensitive+class+or+implement+a+sensitive+interface+must+be+declared+final</a> </p> <p>Example of violations: </p> <pre> class MyPermission extends java.security.Permission { MyPermission(String name) { super(name) } boolean implies(Permission permission) { true } boolean equals(Object obj) { true } int hashCode() { 0 } String getActions() { "action" } } class MyBasicPermission extends BasicPermission { MyBasicPermission(String name) { super(name) } } class MyPrivilegedAction implements PrivilegedAction { Object run() { 0 } } class MyPrivilegedActionException extends PrivilegedActionException { MyPrivilegedActionException(Exception exception) { super(exception) } } </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.security.InsecureRandomRule</key> <severity>MINOR</severity> <name><![CDATA[Insecure Random]]></name> <internalKey><![CDATA[InsecureRandom]]></internalKey> <description><![CDATA[<p>Reports usages of <code>java.util.Random</code>, which can produce very predictable results. If two instances of Random are created with the same seed and sequence of method calls, they will generate the exact same results. Use <code>java.security.SecureRandom</code> instead, which provides a cryptographically strong random number generator. SecureRandom uses PRNG, which means they are using a deterministic algorithm to produce a pseudo-random number from a true random seed. SecureRandom produces non-deterministic output. </p> <p>By default, this rule ignores test classes are ignored. </p> <p>For more information see: <a>http://www.klocwork.com/products/documentation/current/Checkers:SV.RANDOM</a> </p> <p>Example of violations: </p> <pre> def r1 = new Random() def r2 = new java.util.Random() Math.random() java.lang.Math.random() // this is OK new java.security.SecureRandom() new SecureRandom() </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.security.FileCreateTempFileRule</key> <severity>MINOR</severity> <name><![CDATA[File Create Temp File]]></name> <internalKey><![CDATA[FileCreateTempFile]]></internalKey> <description><![CDATA[<p>The File.createTempFile() method is insecure, and has been deprecated by the ESAPI secure coding library. It has been replaced by the ESAPI Randomizer.getRandomFilename(String) method. </p> <p>For more information see the <a href="http://code.google.com/p/owasp-esapi-java/">ESAPI website</a> and the <a href="http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/Randomizer.html">Randomizer Javadoc</a>. </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.security.SystemExitRule</key> <severity>MINOR</severity> <name><![CDATA[System Exit]]></name> <internalKey><![CDATA[SystemExit]]></internalKey> <description><![CDATA[<p>Web applications should never call System.exit(). A call to System.exit() is probably part of leftover debug code or code imported from a non-J2EE application. </p> <p>[[1]] Standards Mapping - OWASP Top 10 2004 - (OWASP 2004) A9 Application Denial of Service </p> <p>[[2]] Standards Mapping - Security Technical Implementation Guide Version 3 - (STIG 3) APP6080 CAT II </p> <p>[[3]] Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 382 </p> <p>[[4]] Standards Mapping - Payment Card Industry Data Security Standard Version 1.1 - (PCI 1.1) Requirement 6.5.9 </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.security.ObjectFinalizeRule</key> <severity>MINOR</severity> <name><![CDATA[Object Finalize]]></name> <internalKey><![CDATA[ObjectFinalize]]></internalKey> <description><![CDATA[<p>The finalize() method should only be called by the JVM after the object has been garbage collected. </p> <p>While the Java Language Specification allows an object's finalize() method to be called from outside the finalizer, doing so is usually a bad idea. For example, calling finalize() explicitly means that finalize() will be called more than once: the first time will be the explicit call and the last time will be the call that is made after the object is garbage collected. </p> <p>References: Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 586 </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.security.JavaIoPackageAccessRule</key> <severity>MINOR</severity> <name><![CDATA[Java Io Package Access]]></name> <internalKey><![CDATA[JavaIoPackageAccess]]></internalKey> <description><![CDATA[<p>This rule reports violations of the Enterprise JavaBeans specification by using the java.io package to access files or the file system. </p> <p>The Enterprise JavaBeans specification requires that every bean provider follow a set of programming guidelines designed to ensure that the bean will be portable and behave consistently in any EJB container [1]. </p> <p>In this case, the program violates the following EJB guideline: "An enterprise bean must not use the java.io package to attempt to access files and directories in the file system." </p> <p>A requirement that the specification justifies in the following way: "The file system APIs are not well-suited for business components to access data. Business components should use a resource manager API, such as JDBC, to store data." </p> <p>REFERENCES </p> <p>[[1]] Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 576 </p> <p>[[2]] The Enterprise JavaBeans 2.1 Specification Sun Microsystems </p> By default, this rule is not applied to tests and test cases. </p> <p>Example of violations: </p> <pre> FileSystem.getFileSystem() // any method on FileSystem FileSystem.fileSystem.delete(aFile) // property access of FileSystem // shouldn't create files new File(name) new File(name, parent) // don't create file readers new FileReader(name) // don't create file output streams new FileOutputStream(name) new FileOutputStream(name, true) // don't create random access file new RandomAccessFile(name, parent) </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.security.UnsafeArrayDeclarationRule</key> <severity>MINOR</severity> <name><![CDATA[Unsafe Array Declaration]]></name> <internalKey><![CDATA[UnsafeArrayDeclaration]]></internalKey> <description><![CDATA[<p>Triggers a violation when an array is declared public, final, and static. </p> <p>In most cases an array declared public, final and static is a bug. Because arrays are mutable objects, the final constraint requires that the array object itself be assigned only once, but makes no guarantees about the values of the array elements. Since the array is public, a malicious program can change the values stored in the array. In most situations the array should be made private. </p> <p>Example of violations: </p> <pre> class MyClass { public static final String[] myArray = init() public static final def myArray = [] as String[] } </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.security.PublicFinalizeMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Public Finalize Method]]></name> <internalKey><![CDATA[PublicFinalizeMethod]]></internalKey> <description><![CDATA[<p>Creates a violation when the program violates secure coding principles by declaring a <code>finalize()</code> method public. </p> <p>A program should never call finalize explicitly, except to call super.finalize() inside an implementation of <code>finalize()</code>. In mobile code situations, the otherwise error prone practice of manual garbage collection can become a security threat if an attacker can maliciously invoke one of your finalize() methods because it is declared with public access. If you are using <code>finalize()</code> as it was designed, there is no reason to declare <code>finalize()</code> with anything other than protected access. </p> <p>References: </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.security.NonFinalPublicFieldRule</key> <severity>MINOR</severity> <name><![CDATA[Non Final Public Field]]></name> <internalKey><![CDATA[NonFinalPublicField]]></internalKey> <description><![CDATA[<p>Finds code that violates secure coding principles for mobile code by declaring a member variable public but not final. </p> <p>All public member variables in an Applet and in classes used by an Applet should be declared final to prevent an attacker from manipulating or gaining unauthorized access to the internal state of the Applet. </p> <p>References: </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.security.UnsafeImplementationAsMapRule</key> <severity>MINOR</severity> <name><![CDATA[Unsafe Implementation As Map]]></name> <internalKey><![CDATA[UnsafeImplementationAsMap]]></internalKey> <description><![CDATA[<p>Reports incomplete interface implementations created by map-to-interface coercions. </p> <p>By default, this rule does not apply to test files. </p> <p>NOTE: This is a <a href="http://codenarc.sourceforge.net/codenarc-enhanced-classpath-rules.html">CodeNarc Enhanced Classpath Rule</a>. It requires <code>CodeNarc</code> to have the application classes being analyzed, as well as any referenced classes, on the classpath. </p> <p>Example of violations: </p> <pre> [mouseClicked: { ... }] as MouseListener //not all MouseListener methods are implemented which can lead to UnsupportedOperationException-s </pre> ]]></description> <tag>bug</tag> </rule> <!-- formatting rules --> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.formatting.BracesForClassRule</key> <severity>MINOR</severity> <name><![CDATA[Braces For Class]]></name> <internalKey><![CDATA[BracesForClass]]></internalKey> <description><![CDATA[<p>Checks the location of the opening brace (\{) for classes. By default, requires them on the same line, but the <code>sameLine</code> property can be set to false to override this. </p> <p>NOTE: This rule ignores annotation types, e.g. <code>@interface MyAnnotation {}</code>. </p> ]]></description> <tag>convention</tag> <param> <key>sameLine</key> <defaultValue>true</defaultValue> </param> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.formatting.LineLengthRule</key> <severity>MINOR</severity> <name><![CDATA[Line Length]]></name> <internalKey><![CDATA[LineLength]]></internalKey> <description><![CDATA[<p>Checks the maximum length for each line of source code. It checks for number of characters, so lines that include tabs may appear longer than the allowed number when viewing the file. The maximum line length can be configured by setting the length property, which defaults to 120. </p> <p>NOTE: This rule does not support the @SuppressAnnotations annotation or the classname-based rule properties (applyToClassNames, doNotApplyToClassNames) to enable/disable the rule. If you want to specify or restrict where this rule is applied, you must use the file-based rule properties: applyToFileNames, doNotApplyToFileNames, applyToFilesMatching and doNotApplyToFilesMatching. </p> ]]></description> <tag>convention</tag> <param> <key>ignoreImportStatements</key> <description><![CDATA[If true, then do not apply this rule to import statements. ]]></description> <defaultValue>true</defaultValue> </param> <param> <key>ignoreLineRegex</key> <description><![CDATA[If specified, then ignore lines matching this regular expression. ]]></description> </param> <param> <key>ignorePackageStatements</key> <description><![CDATA[If true, then do not apply this rule to package statements. ]]></description> <defaultValue>true</defaultValue> </param> <param> <key>length</key> <description><![CDATA[The maximum line length allowed. ]]></description> <defaultValue>120</defaultValue> </param> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.formatting.BracesForForLoopRule</key> <severity>MINOR</severity> <name><![CDATA[Braces For For Loop]]></name> <internalKey><![CDATA[BracesForForLoop]]></internalKey> <description><![CDATA[<p>Checks the location of the opening brace (\{) for for loops. By default, requires them on the same line, but the <code>sameLine</code> property can be set to false to override this. </p> ]]></description> <tag>convention</tag> <param> <key>sameLine</key> <defaultValue>true</defaultValue> </param> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.formatting.BracesForIfElseRule</key> <severity>MINOR</severity> <name><![CDATA[Braces For If Else]]></name> <internalKey><![CDATA[BracesForIfElse]]></internalKey> <description><![CDATA[<p>Checks the location of the opening brace (\{) for if statements. By default, requires them on the same line, but the <code>sameLine</code> property can be set to false to override this. </p> ]]></description> <tag>convention</tag> <param> <key>elseOnSameLineAsClosingBrace</key> <description><![CDATA[If true, then the else statement should be on the same line as closing brace (\}) ]]></description> <defaultValue>true</defaultValue> </param> <param> <key>elseOnSameLineAsOpeningBrace</key> <description><![CDATA[If true, then the else statement should be on the same line as opening brace (\{) ]]></description> <defaultValue>true</defaultValue> </param> <param> <key>sameLine</key> <description><![CDATA[If true, then the opening brace (\{) for if statement should be on the same line. ]]></description> <defaultValue>true</defaultValue> </param> <param> <key>validateElse</key> <description><![CDATA[To enable else checking, set the property to true ]]></description> <defaultValue>false</defaultValue> </param> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.formatting.BracesForMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Braces For Method]]></name> <internalKey><![CDATA[BracesForMethod]]></internalKey> <description><![CDATA[<p>Checks the location of the opening brace (\{) for constructors and methods. By default, requires them on the same line, but the <code>sameLine</code> property can be set to false to override this. </p> ]]></description> <tag>convention</tag> <param> <key>sameLine</key> <defaultValue>true</defaultValue> </param> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.formatting.BracesForTryCatchFinallyRule</key> <severity>MINOR</severity> <name><![CDATA[Braces For Try Catch Finally]]></name> <internalKey><![CDATA[BracesForTryCatchFinally]]></internalKey> <description><![CDATA[<p>Checks the location of the opening brace (\{) for try statements. By default, requires them on the line, but the <code>sameLine</code> property can be set to false to override this. </p> ]]></description> <tag>convention</tag> <param> <key>sameLine</key> <defaultValue>true</defaultValue> </param> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.formatting.ClassJavadocRule</key> <severity>MINOR</severity> <name><![CDATA[Class Javadoc]]></name> <internalKey><![CDATA[ClassJavadoc]]></internalKey> <description><![CDATA[<p>Makes sure each class and interface definition is preceded by javadoc. Enum definitions are not checked, due to strange behavior in the Groovy AST. By default, only the main class in a file is checked for Javadoc. The main class is defined as the class that has the same name as the source file, for instance MyClass is the main class in MyClass.groovy but the class MyOtherClass defined in the same source file is not the main class. To check all the classes in the file set the rule property <code>applyToNonMainClasses</code> to true. </p> ]]></description> <tag>convention</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceAfterCommaRule</key> <severity>MAJOR</severity> <name><![CDATA[Space After Comma]]></name> <internalKey><![CDATA[SpaceAfterComma]]></internalKey> <description><![CDATA[<p>Checks that there is at least one space or whitespace following each comma. That includes checks for method and closure declaration parameter lists, method call parameter lists, Map literals and List literals. </p> <p>Known limitations: </p> ]]></description> <tag>convention</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceAfterSemicolonRule</key> <severity>MAJOR</severity> <name><![CDATA[Space After Semicolon]]></name> <internalKey><![CDATA[SpaceAfterSemicolon]]></internalKey> <description><![CDATA[<p>Check that there is at least one space (blank) or whitespace following a semicolon that separates: </p> ]]></description> <tag>convention</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceAroundOperatorRule</key> <severity>MAJOR</severity> <name><![CDATA[Space Around Operator]]></name> <internalKey><![CDATA[SpaceAroundOperator]]></internalKey> <description><![CDATA[<p>Check that there is at least one space (blank) or whitespace around each binary operator, including: +, -, *, /, \>\>, \<\<, &&, ||, &, |, ?:, =, "as". </p> <p>Do not check dot ('.') operator. Do not check unary operators (!, +, -, ++, --, ?.). Do not check array ('[') operator. </p> <p>Known limitations: </p> ]]></description> <tag>convention</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceBeforeOpeningBraceRule</key> <severity>MAJOR</severity> <name><![CDATA[Space Before Opening Brace]]></name> <internalKey><![CDATA[SpaceBeforeOpeningBrace]]></internalKey> <description><![CDATA[<p>Check that there is at least one space (blank) or whitespace before each opening brace ("\{") for method/class/interface declarations, closure expressions and block statements. </p> <p>Known limitations: </p> ]]></description> <tag>convention</tag> <param> <key>checkClosureMapEntryValue</key> <description><![CDATA[If false, then do not check for whitespace before opening braces for closure expressions that are literal Map values, e.g. [abc:{doStuff()}]. ]]></description> <defaultValue>true</defaultValue> </param> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceAfterOpeningBraceRule</key> <severity>MAJOR</severity> <name><![CDATA[Space After Opening Brace]]></name> <internalKey><![CDATA[SpaceAfterOpeningBrace]]></internalKey> <description><![CDATA[<p>Check that there is at least one space (blank) or whitespace after each opening brace ("\{") for method/class/interface declarations, closure expressions and block statements. </p> Examples of violations: </p> <pre> class MyClass{int count } // violation interface MyInterface {static final OK = 1 }// violation enum MyEnum {OK, BAD } // violation def myMethod() {int count } // violation if (ready) {println 9 } // violation if (ready) { } else {println 99} // violation for (int i=0; i<10; i++) {println i } // violation for (String name in names) {println name } // violation for (String name: names) {println name } // violation while (ready) {println time } // violation try {doStuff() // violation } catch(Exception e) {x=77 } // violation } finally {println 'error' } // violation list.each {name -> } // violation shouldFail(Exception) {doStuff() } // violation </pre> ]]></description> <tag>convention</tag> <param> <key>checkClosureMapEntryValue</key> <description><![CDATA[If false, then do not check for whitespace after opening braces for closure expressions that are literal Map values, e.g. [abc:{doStuff()}]. ]]></description> <defaultValue>true</defaultValue> </param> <param> <key>ignoreEmptyBlock</key> <description><![CDATA[If true, then allow for [{}] in code ]]></description> <defaultValue>false</defaultValue> </param> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceAfterClosingBraceRule</key> <severity>MAJOR</severity> <name><![CDATA[Space After Closing Brace]]></name> <internalKey><![CDATA[SpaceAfterClosingBrace]]></internalKey> <description><![CDATA[<p>Check that there is at least one space (blank) or whitespace after each closing brace ("\{") for method/class/interface declarations, closure expressions and block statements. </p> <p>A closure expression followed by a dot operator (.), a comma, a closing parenthesis, the spread-dot operator (*.), a semicolon or the null-safe operator (?.) does not cause a violation. </p> Known limitations: </p> ]]></description> <tag>convention</tag> <param> <key>checkClosureMapEntryValue</key> <description><![CDATA[If false, then do not check for whitespace after closing braces for closure expressions that are literal Map values, e.g. [abc:{doStuff()}]. ]]></description> <defaultValue>true</defaultValue> </param> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceBeforeClosingBraceRule</key> <severity>MAJOR</severity> <name><![CDATA[Space Before Closing Brace]]></name> <internalKey><![CDATA[SpaceBeforeClosingBrace]]></internalKey> <description><![CDATA[<p>Check that there is at least one space (blank) or whitespace before each closing brace ("\}") for method/class/interface declarations, closure expressions and block statements. </p> <p>Known limitations: </p> ]]></description> <tag>convention</tag> <param> <key>checkClosureMapEntryValue</key> <description><![CDATA[If false, then do not check for whitespace before closing braces for closure expressions that are literal Map values, e.g. [abc:{doStuff()}]. ]]></description> <defaultValue>true</defaultValue> </param> <param> <key>ignoreEmptyBlock</key> <description><![CDATA[If true, then allow for [{}] in code ]]></description> <defaultValue>false</defaultValue> </param> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceAfterIfRule</key> <severity>MAJOR</severity> <name><![CDATA[Space After If]]></name> <internalKey><![CDATA[SpaceAfterIf]]></internalKey> <description><![CDATA[<p>Check that there is exactly one space (blank) after the <code>if</code> keyword and before the opening parenthesis. </p> <p>Examples of violations: </p> <pre> if(true) { } // violation if (true) { } // violation </pre> ]]></description> <tag>convention</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceAfterWhileRule</key> <severity>MAJOR</severity> <name><![CDATA[Space After While]]></name> <internalKey><![CDATA[SpaceAfterWhile]]></internalKey> <description><![CDATA[<p>Check that there is exactly one space (blank) after the <code>while</code> keyword and before the opening parenthesis. </p> <p>Examples of violations: </p> <pre> while(true) { } // violation while (true) { } // violation </pre> ]]></description> <tag>convention</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceAfterForRule</key> <severity>MAJOR</severity> <name><![CDATA[Space After For]]></name> <internalKey><![CDATA[SpaceAfterFor]]></internalKey> <description><![CDATA[<p>Check that there is exactly one space (blank) after the <code>for</code> keyword and before the opening parenthesis. </p> <p>Examples of violations: </p> <pre> for(name in names) { } // violation for (int i=0; i < 10; i++) { } // violation </pre> ]]></description> <tag>convention</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceAfterSwitchRule</key> <severity>MAJOR</severity> <name><![CDATA[Space After Switch]]></name> <internalKey><![CDATA[SpaceAfterSwitch]]></internalKey> <description><![CDATA[<p>Check that there is exactly one space (blank) after the <code>switch</code> keyword and before the opening parenthesis. </p> <p>Examples of violations: </p> <pre> switch(x) { // violation case 1: println 'one' } switch (x) { // violation case 1: println 'one' } </pre> ]]></description> <tag>convention</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.formatting.SpaceAfterCatchRule</key> <severity>MAJOR</severity> <name><![CDATA[Space After Catch]]></name> <internalKey><![CDATA[SpaceAfterCatch]]></internalKey> <description><![CDATA[<p>Check that there is exactly one space (blank) after the <code>catch</code> keyword and before the opening parenthesis. </p> <p>Examples of violations: </p> <pre> try { } catch(Exception e) { } // violation try { } catch (Exception e) { } // violation </pre> ]]></description> <tag>convention</tag> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.formatting.SpaceAroundClosureArrowRule</key> <severity>MAJOR</severity> <name><![CDATA[Space Around Closure Arrow]]></name> <internalKey><![CDATA[SpaceAroundClosureArrow]]></internalKey> <description><![CDATA[<p>Checks that there is at least one space (blank) or whitespace around each closure arrow (->) symbol. </p> <p>Known limitations: </p> ]]></description> <tag>convention</tag> </rule> <!-- since 0.20 --> <rule> <key>org.codenarc.rule.formatting.SpaceAroundMapEntryColonRule</key> <severity>MAJOR</severity> <name><![CDATA[Space Around Map Entry Colon]]></name> <internalKey><![CDATA[SpaceAroundMapEntryColon]]></internalKey> <description><![CDATA[<p>Check for proper formatting of whitespace around colons for literal Map entries. By default, no whitespace is allowed either before or after the Map entry colon, but you can change that through the configuration properties below. </p> <p>Example of violations: </p> <pre> Map m1 = [myKey : 12345] // violation (both before and after the colon) println [a :[1:11, 2:22], // violation on a (before colon) b:[(Integer): 33]] // violation on Integer (after colon) </pre> ]]></description> <tag>convention</tag> <param> <key>characterAfterColonRegex</key> <description><![CDATA[The regular expression that must match the character after the colon (:) for a literal <Map> entry. For example, /\\S/ matches any non-whitespace character and /\\s/ matches any whitespace character (thus requiring a space or whitespace). ]]></description> <defaultValue>\\S</defaultValue> </param> <param> <key>characterBeforeColonRegex</key> <description><![CDATA[The regular expression that must match the character before the colon (:) for a literal <Map> entry. For example, /\\S/ matches any non-whitespace character and /\\s/ matches any whitespace character (thus requiring a space or whitespace). ]]></description> <defaultValue>\\S</defaultValue> </param> </rule> <!-- since 0.20 --> <rule> <key>org.codenarc.rule.formatting.ClosureStatementOnOpeningLineOfMultipleLineClosureRule</key> <severity>MAJOR</severity> <name><![CDATA[Closure Statement On Opening Line Of Multiple Line Closure]]></name> <internalKey><![CDATA[ClosureStatementOnOpeningLineOfMultipleLineClosure]]></internalKey> <description><![CDATA[<p>Checks for closure logic on first line (after <code>-\</code</code>) for a multi-line closure. That breaks the symmetry of indentation (if the subsequent statements are indented normally), and that first statement can be easily missed when reading the code. </p> <p>Example of violations: </p> <pre> def closure = { name -> println name addToCounts() println “done” } </pre> ]]></description> <tag>convention</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.formatting.ConsecutiveBlankLinesRule</key> <severity>MAJOR</severity> <name><![CDATA[Consecutive Blank Lines]]></name> <internalKey><![CDATA[ConsecutiveBlankLines]]></internalKey> <description><![CDATA[<p>Makes sure there are no consecutive lines that are either blank or whitespace only. This reduces the need to scroll further than necessary when reading code, and increases the likelihood that a logical block of code will fit on one screen for easier comprehension. </p> <p>Example of violation: </p> <pre> def name def value def id </pre> ]]></description> <tag>convention</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.formatting.BlankLineBeforePackageRule</key> <severity>MAJOR</severity> <name><![CDATA[Blank Line Before Package]]></name> <internalKey><![CDATA[BlankLineBeforePackage]]></internalKey> <description><![CDATA[<p>Makes sure there are no blank lines before the package declaration of a source code file. </p> ]]></description> <tag>convention</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.formatting.FileEndsWithoutNewlineRule</key> <severity>MAJOR</severity> <name><![CDATA[File Ends Without Newline]]></name> <internalKey><![CDATA[FileEndsWithoutNewline]]></internalKey> <description><![CDATA[<p>Makes sure each source file ends with a newline character. </p> ]]></description> <tag>convention</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.formatting.MissingBlankLineAfterImportsRule</key> <severity>MAJOR</severity> <name><![CDATA[Missing Blank Line After Imports]]></name> <internalKey><![CDATA[MissingBlankLineAfterImports]]></internalKey> <description><![CDATA[<p>Makes sure there is a blank line after the imports of a source code file. </p> <p>Example of violation: </p> <pre> import org.apache.commons.lang.StringUtils class MyClass { } // violation </pre> ]]></description> <tag>convention</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.formatting.MissingBlankLineAfterPackageRule</key> <severity>MAJOR</severity> <name><![CDATA[Missing Blank Line After Package]]></name> <internalKey><![CDATA[MissingBlankLineAfterPackage]]></internalKey> <description><![CDATA[<p>Makes sure there is a blank line after the package statement of a source code file. </p> <p>Example of violation: </p> <pre> package org.codenarc import java.util.Date // violation class MyClass { void go() { /* ... */ } } </pre> ]]></description> <tag>convention</tag> </rule> <!-- since 0.21 --> <rule> <key>org.codenarc.rule.formatting.TrailingWhitespaceRule</key> <severity>MAJOR</severity> <name><![CDATA[Trailing Whitespace]]></name> <internalKey><![CDATA[TrailingWhitespace]]></internalKey> <description><![CDATA[<p>Checks that no lines of source code end with whitespace characters. </p> ]]></description> <tag>convention</tag> </rule> <!-- convention rules --> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.convention.InvertedIfElseRule</key> <severity>MAJOR</severity> <name><![CDATA[Inverted If Else]]></name> <internalKey><![CDATA[InvertedIfElse]]></internalKey> <description><![CDATA[<p>An inverted <if-else> statement is one in which there is a single <code>if</code> statement with a single <code>else</code> branch and the boolean test of the <code>if</code> is negated. For instance <code>if (!x) false else true</code>. It is usually clearer to write this as <code>if (x) true else false</code>. </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.12 --> <rule> <key>org.codenarc.rule.convention.ConfusingTernaryRule</key> <severity>MAJOR</severity> <name><![CDATA[Confusing Ternary]]></name> <internalKey><![CDATA[ConfusingTernary]]></internalKey> <description><![CDATA[<p>In a ternary expression avoid negation in the test. For example, rephrase: <code>(x != y) ? diff : same</code> as: <code>(x == y) ? same : diff</code>. Consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as "does the error case go first?" or "does the common case go first?". </p> <p>Example: </p> <pre> (x != y) ? diff : same // triggers violation (!x) ? diff : same // triggers violation (x == y) ? same : diff // OK (x) ? same : diff // OK // this is OK, because of GroovyTruth there is no inverse of != null (x != null) ? diff : same // this is OK, because of GroovyTruth there is no inverse of != true (x != true) ? diff : same // this is OK, because of GroovyTruth there is no inverse of != false (x != false) ? diff : same </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.convention.CouldBeElvisRule</key> <severity>MAJOR</severity> <name><![CDATA[Could Be Elvis]]></name> <internalKey><![CDATA[CouldBeElvis]]></internalKey> <description><![CDATA[<p>Catch an if block that could be written as an elvis expression. </p> <p>Example of violations: </p> <pre> if (!x) { // violation x = 'some value' } if (!x) // violation x = "some value" if (!params.max) { // violation params.max = 10 } x ?: 'some value' // OK </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.convention.LongLiteralWithLowerCaseLRule</key> <severity>MINOR</severity> <name><![CDATA[Long Literal With Lower Case L]]></name> <internalKey><![CDATA[LongLiteralWithLowerCaseL]]></internalKey> <description><![CDATA[<p>In Java and Groovy, you can specify long literals with the L or l character, for instance 55L or 24l. It is best practice to always use an uppercase L and never a lowercase l. This is because 11l rendered in some fonts may look like 111 instead of 11L. </p> <p>Example of violations: </p> <pre> def x = 1l def y = 55l </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.17 --> <rule> <key>org.codenarc.rule.convention.ParameterReassignmentRule</key> <severity>MAJOR</severity> <name><![CDATA[Parameter Reassignment]]></name> <internalKey><![CDATA[ParameterReassignment]]></internalKey> <description><![CDATA[<p>Checks for a method or closure parameter being reassigned to a new value within the body of the method/closure, which is a confusing and questionable practice. Use a temporary variable instead. </p> <p>Example of violations: </p> <pre> void myMethod(int a, String b) { println a b = 'new value' // violation } def myClosure1 = { int a, b -> a = 123 // violation } </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.17 --> <rule> <key>org.codenarc.rule.convention.TernaryCouldBeElvisRule</key> <severity>MAJOR</severity> <name><![CDATA[Ternary Could Be Elvis]]></name> <internalKey><![CDATA[TernaryCouldBeElvis]]></internalKey> <description><![CDATA[<p>Checks for ternary expressions where the <boolean> and <true> expressions are the same. These can be simplified to an <Elvis> expression. </p> <p>Example of violations: </p> <pre> x ? x : false // violation; can simplify to x ?: false foo() ? foo() : bar() // violation; can simplify to foo() ?: bar() foo(1) ? foo(1) : 123 // violation; can simplify to foo(1) ?: 123 (x == y) ? same : diff // OK x ? y : z // OK x ? x + 1 : x + 2 // OK x ? 1 : 0 // OK x ? !x : x // OK !x ? x : null // OK foo() ? bar() : 123 // OK foo() ? foo(99) : 123 // OK foo(x) ? foo() : 123 // OK foo(1) ? foo(2) : 123 // OK </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.17 --> <rule> <key>org.codenarc.rule.convention.VectorIsObsoleteRule</key> <severity>MINOR</severity> <name><![CDATA[Vector Is Obsolete]]></name> <internalKey><![CDATA[VectorIsObsolete]]></internalKey> <description><![CDATA[<p>Checks for references to the (<effectively>) obsolete <code>java.util.Vector</code> class. Use the <code>Java Collections Framework</code> classes instead, including <code>ArrayList</code> or <code>Collections.synchronizedList()</code>. See the JDK javadoc. </p> <p>Example of violations: </p> <pre> def myList = new Vector() // violation </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.17 --> <rule> <key>org.codenarc.rule.convention.HashtableIsObsoleteRule</key> <severity>MINOR</severity> <name><![CDATA[Hashtable Is Obsolete]]></name> <internalKey><![CDATA[HashtableIsObsolete]]></internalKey> <description><![CDATA[<p>Checks for references to the (<effectively>) obsolete <code>java.util.Hashtable</code> class. Use the <code>Java Collections Framework</code> classes instead, including <code>HashMap</code> or <code>ConcurrentHashMap</code>. See the JDK javadoc. </p> <p>Example of violations: </p> <pre> def myMap = new Hashtable() // violation </pre> ]]></description> <tag>bug</tag> </rule> <!-- since 0.18 --> <rule> <key>org.codenarc.rule.convention.IfStatementCouldBeTernaryRule</key> <severity>MINOR</severity> <name><![CDATA[If Statement Could Be Ternary]]></name> <internalKey><![CDATA[IfStatementCouldBeTernary]]></internalKey> <description><![CDATA[<p>Checks for: </p> ]]></description> <tag>bug</tag> </rule> <!-- since 0.22 --> <rule> <key>org.codenarc.rule.convention.NoDefRule</key> <severity>MAJOR</severity> <name><![CDATA[No Def]]></name> <internalKey><![CDATA[NoDef]]></internalKey> <description><![CDATA[<p> Do not allow using the <code>def</code> keyword in code. Use a specific type instead. </p> <p><code>NOTE:</code> This rule applies to the text contents of a <file> rather than a specific <class>, so it does not support the <applyToClassNames> and <doNotApplyToClassNames> configuration properties. </p> ]]></description> <tag>bug</tag> <param> <key>excludeRegex</key> <description><![CDATA[Regular expression describing names of attributes, parameters or methods that could be precede by the def keyword. ]]></description> </param> </rule> <!-- since 0.25 --> <rule> <key>org.codenarc.rule.convention.TrailingCommaRule</key> <severity>MAJOR</severity> <name><![CDATA[Trailing Comma]]></name> <internalKey><![CDATA[TrailingComma]]></internalKey> <description><![CDATA[<p>Check whether list and map literals contain optional trailing comma. Rationale: Putting this comma in make is easier to change the order of the elements or add new elements on the end. </p> <p>This is valid code: </p> <pre> int[] array1 = [] // one line declaration int[] array2 = [ // empty list ] int[] array3 = [1,2,3] // one line declaration int[] array4 = [1, 2, 3, // contains trailing comma ] </pre> <pre> int[] array2 = [1, 2 // there is no trailing comma ] </pre> ]]></description> <tag>bug</tag> <param> <key>checkList</key> <description><![CDATA[To disable checking List literals, set this property to false ]]></description> <defaultValue>true</defaultValue> </param> <param> <key>checkMap</key> <description><![CDATA[To disable checking Map literals, set this property to false ]]></description> <defaultValue>true</defaultValue> </param> </rule> <!-- since 0.25 --> <rule> <key>org.codenarc.rule.convention.NoTabCharacterRule</key> <severity>MAJOR</severity> <name><![CDATA[No Tab Character]]></name> <internalKey><![CDATA[NoTabCharacter]]></internalKey> <description><![CDATA[<p>Checks that all source files do not contain the tab character. </p> ]]></description> <tag>bug</tag> </rule> <!-- groovyism rules --> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitArrayListInstantiationRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Array List Instantiation]]></name> <internalKey><![CDATA[ExplicitArrayListInstantiation]]></internalKey> <description><![CDATA[<p>This rule checks for explicit calls to the no-argument constructor of <code>ArrayList</code>. In Groovy, it is best to write <code>new ArrayList() as []</code>, which creates the same object. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToAndMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To And Method]]></name> <internalKey><![CDATA[ExplicitCallToAndMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>and(Object)</code> method is called directly in code instead of using the <code>&</code> operator. A groovier way to express this: <code>a.and(b)</code> is this: <code>a & b</code>. This rule can be configured to ignore <code>this.and(Object)</code> using the <ignoreThisReference> property. It defaults to <true>, so even <code>and(x)</code> will not trigger a violation. The default is <true> because <code>and</code> appears commonly in Grails criteria. </p> <p>This rule also ignores all calls to <code>super.and(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToCompareToMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Compare To Method]]></name> <internalKey><![CDATA[ExplicitCallToCompareToMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>compareTo(Object)</code> method is called directly in code instead of using the \<\=\>, \>, \>\=, \<, and \<\= operators. A groovier way to express this: <code>a.compareTo(b)</code> is this: <code>a \<\=\> b</code>, or using the other operators. Here are some other ways to write groovier code: </p> <pre> a.compareTo(b) == 0 // can be replaced by: a == b a.compareTo(b) // can be replaced by: a <=> b a.compareTo(b) > 0 // can be replaced by: a > b a.compareTo(b) >= 0 // can be replaced by: a >= b a.compareTo(b) < 0 // can be replaced by: a < b a.compareTo(b) <= 0 // can be replaced by: a <= b </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToDivMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Div Method]]></name> <internalKey><![CDATA[ExplicitCallToDivMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>div(Object)</code> method is called directly in code instead of using the <code>/</code> operator. A groovier way to express this: <code>a.div(b)</code> is this: <code>a / b</code>. This rule can be configured to ignore <code>div.xor(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>div(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.div(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToEqualsMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Equals Method]]></name> <internalKey><![CDATA[ExplicitCallToEqualsMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>equals(Object)</code> method is called directly in code instead of using the <code>==</code> or <code>!=</code> operator. A groovier way to express this: <code>a.equals(b)</code> is this: <code>a == b</code> and a groovier way to express : <code>!a.equals(b)</code> is: <code>a != b</code>. This rule can be configured to ignore <code>this.equals(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>equals(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.equals(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToGetAtMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Get At Method]]></name> <internalKey><![CDATA[ExplicitCallToGetAtMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>getAt(Object)</code> method is called directly in code instead of using the <code>[]</code> index operator. A groovier way to express this: <code>a.getAt(b)</code> is this: <code>a[b]</code>. This rule can be configured to ignore <code>this.getAt(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>getAt(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.getAt(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToLeftShiftMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Left Shift Method]]></name> <internalKey><![CDATA[ExplicitCallToLeftShiftMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>leftShift(Object)</code> method is called directly in code instead of using the \<\< operator. A groovier way to express this: <code>a.leftShift(b)</code> is this: <code>a \<\< b</code>. This rule can be configured to ignore <code>this.leftShift(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>leftShift(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.leftShift(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToMinusMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Minus Method]]></name> <internalKey><![CDATA[ExplicitCallToMinusMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>minus(Object)</code> method is called directly in code instead of using the <code>-</code> operator. A groovier way to express this: <code>a.minus(b)</code> is this: <code>a - b</code>. This rule can be configured to ignore <code>minus.xor(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>minus(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.minus(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToMultiplyMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Multiply Method]]></name> <internalKey><![CDATA[ExplicitCallToMultiplyMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>multiply(Object)</code> method is called directly in code instead of using the <code>*</code> operator. A groovier way to express this: <code>a.multiply(b)</code> is this: <code>a * b</code>. This rule can be configured to ignore <code>this.multiply(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>multiply(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.multiply(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToModMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Mod Method]]></name> <internalKey><![CDATA[ExplicitCallToModMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>mod(Object)</code> method is called directly in code instead of using the <code>%</code> operator. A groovier way to express this: <code>a.mod(b)</code> is this: <code>a % b</code>. This rule can be configured to ignore <code>this.mod(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>mod(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.mod(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToOrMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Or Method]]></name> <internalKey><![CDATA[ExplicitCallToOrMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>or(Object)</code> method is called directly in code instead of using the <code>|</code> operator. A groovier way to express this: <code>a.or(b)</code> is this: <code>a | b</code>. This rule can be configured to ignore <code>this.or(Object)</code> using the <ignoreThisReference> property. It defaults to <true>, so even <code>or(x)</code> will not trigger a violation. This is the default because it is commonly used in Grails criteria. </p> <p>This rule also ignores all calls to <code>super.or(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToPlusMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Plus Method]]></name> <internalKey><![CDATA[ExplicitCallToPlusMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>plus(Object)</code> method is called directly in code instead of using the <code>+</code> operator. A groovier way to express this: <code>a.plus(b)</code> is this: <code>a + b</code>. This rule can be configured to ignore <code>this.plus(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>plus(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.plus(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToPowerMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Power Method]]></name> <internalKey><![CDATA[ExplicitCallToPowerMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>power(Object)</code> method is called directly in code instead of using the <code>**</code> operator. A groovier way to express this: <code>a.power(b)</code> is this: <code>a ** b</code>. This rule can be configured to ignore <code>this.power(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>power(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.power(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToRightShiftMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Right Shift Method]]></name> <internalKey><![CDATA[ExplicitCallToRightShiftMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>rightShift(Object)</code> method is called directly in code instead of using the \>\> operator. A groovier way to express this: <code>a.rightShift(b)</code> is this: <code>a \>\> b</code>. This rule can be configured to ignore <code>this.rightShift(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>rightShift(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.rightShift(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitCallToXorMethodRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Call To Xor Method]]></name> <internalKey><![CDATA[ExplicitCallToXorMethod]]></internalKey> <description><![CDATA[<p>This rule detects when the <code>xor(Object)</code> method is called directly in code instead of using the <code>^</code> operator. A groovier way to express this: <code>a.xor(b)</code> is this: <code>a ^ b</code>. This rule can be configured to ignore <code>this.xor(Object)</code> using the <ignoreThisReference> property. It defaults to <false>, so even <code>xor(x)</code> will trigger a violation. </p> <p>This rule also ignores all calls to <code>super.xor(Object)</code>. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitHashMapInstantiationRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Hash Map Instantiation]]></name> <internalKey><![CDATA[ExplicitHashMapInstantiation]]></internalKey> <description><![CDATA[<p>This rule checks for explicit calls to the no-argument constructor of <code>HashMap</code>. In Groovy, it is best to replace <code>new HashMap()</code> with <code>[:]</code>, which creates (mostly) the same object. <code>[:]</code> is technically a LinkedHashMap but it is very rare that someone absolutely needs an instance of <code>HashMap</code> and not a subclass. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitHashSetInstantiationRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Hash Set Instantiation]]></name> <internalKey><![CDATA[ExplicitHashSetInstantiation]]></internalKey> <description><![CDATA[<p>This rule checks for explicit calls to the no-argument constructor of <code>HashSet</code>. In Groovy, it is best to replace <code>new HashSet()</code> with <code>[] as Set</code>, which creates the same object. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitLinkedListInstantiationRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Linked List Instantiation]]></name> <internalKey><![CDATA[ExplicitLinkedListInstantiation]]></internalKey> <description><![CDATA[<p>This rule checks for explicit calls to the no-argument constructor of <code>LinkedList</code>. In Groovy, it is best to replace <code>new LinkedList()</code> with <code>[] as Queue</code>, which creates the same object. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitStackInstantiationRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Stack Instantiation]]></name> <internalKey><![CDATA[ExplicitStackInstantiation]]></internalKey> <description><![CDATA[<p>This rule checks for explicit calls to the no-argument constructor of <code>Stack</code>. In Groovy, it is best to replace <code>new Stack()</code> with <code>[] as Stack</code>, which creates the same object. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitTreeSetInstantiationRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Tree Set Instantiation]]></name> <internalKey><![CDATA[ExplicitTreeSetInstantiation]]></internalKey> <description><![CDATA[<p>This rule checks for explicit calls to the no-argument constructor of <code>TreeSet</code>. In Groovy, it is best to replace <code>new TreeSet()</code> with <code>[] as SortedSet</code>, which creates the same object. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.11 --> <rule> <key>org.codenarc.rule.groovyism.GStringAsMapKeyRule</key> <severity>MINOR</severity> <name><![CDATA[G String As Map Key]]></name> <internalKey><![CDATA[GStringAsMapKey]]></internalKey> <description><![CDATA[<p> A GString should not be used as a map key since its <hashcode> is not guaranteed to be stable. Consider calling <code>key.toString()</code>. </p> <p>Here is an example of code that produces a violation: </p> <pre> Map map = ["${someRef}" : 'invalid' ] // violation </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.13 --> <rule> <key>org.codenarc.rule.groovyism.GroovyLangImmutableRule</key> <severity>MINOR</severity> <name><![CDATA[Groovy Lang Immutable]]></name> <internalKey><![CDATA[GroovyLangImmutable]]></internalKey> <description><![CDATA[<p>The <code>groovy.lang.Immutable</code> annotation has been deprecated and replaced by <code>groovy.transform.Immutable</code>. Do not use the <code>Immutable</code> in <code>groovy.lang</code>. </p> <p>Example of violations: </p> <pre> @Immutable class Person { } @groovy.lang.Immutable class Person { } import groovy.lang.Immutable as Imtl @Imtl class Person { } // the following code is OK @groovy.transform.Immutable class Person { } import groovy.transform.Immutable @Immutable class Person { } import groovy.transform.* @Immutable class Person { } import groovy.transform.Immutable as Imtl @Imtl class Person { } </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.groovyism.ExplicitLinkedHashMapInstantiationRule</key> <severity>MINOR</severity> <name><![CDATA[Explicit Linked Hash Map Instantiation]]></name> <internalKey><![CDATA[ExplicitLinkedHashMapInstantiation]]></internalKey> <description><![CDATA[<p>This rule checks for the explicit instantiation of a <code>LinkedHashMap</code> using the no-arg constructor. In Groovy, it is best to replace <code>new LinkedHashMap()</code> with <code>[:]</code>, which creates the same object. </p> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.14 --> <rule> <key>org.codenarc.rule.groovyism.ClosureAsLastMethodParameterRule</key> <severity>MAJOR</severity> <name><![CDATA[Closure As Last Method Parameter]]></name> <internalKey><![CDATA[ClosureAsLastMethodParameter]]></internalKey> <description><![CDATA[<p>If a method is called and the last parameter is an inline closure then it can be declared outside of the method call parentheses. </p> <p>Example of violations: </p> <pre> // creates violation: poor Groovy style [1,2,3].each({ println it }) // no violation [1,2,3].each { println it } </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.15 --> <rule> <key>org.codenarc.rule.groovyism.AssignCollectionUniqueRule</key> <severity>MINOR</severity> <name><![CDATA[Assign Collection Unique]]></name> <internalKey><![CDATA[AssignCollectionUnique]]></internalKey> <description><![CDATA[<p>The Collections.unique() method mutates the list and returns the list as a value. If you are assigning the result of unique() to a variable, then you probably don't realize that you're also modifying the original list as well. This is frequently the cause of subtle bugs. This violation is triggered when a unique() method call appears as the right hand side of an assignment, or when it appears as the first method call in a series of chained method calls. </p> <p>Example of violations: </p> <pre> def a = myList.unique() def b = myList.unique() { it } def c = myList.unique().findAll { x < 1 } </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.groovyism.AssignCollectionSortRule</key> <severity>MINOR</severity> <name><![CDATA[Assign Collection Sort]]></name> <internalKey><![CDATA[AssignCollectionSort]]></internalKey> <description><![CDATA[<p>The Collections.sort() method mutates the list and returns the list as a value. If you are assigning the result of sort() to a variable, then you probably don't realize that you're also modifying the original list as well. This is frequently the cause of subtle bugs. This violation is triggered when a sort() method call appears as the right hand side of an assignment, or when it appears as the first method call in a series of chained method calls. </p> <p>Example of violations: </p> <pre> def a = myList.sort() def b = myList.sort() { it } def c = myList.sort().findAll { x < 1 } </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.groovyism.ConfusingMultipleReturnsRule</key> <severity>MINOR</severity> <name><![CDATA[Confusing Multiple Returns]]></name> <internalKey><![CDATA[ConfusingMultipleReturns]]></internalKey> <description><![CDATA[<p>Multiple return values can be used to set several variables at once. To use multiple return values, the left hand side of the assignment must be enclosed in parenthesis. If not, then you are not using multiple return values, you're only assigning the last element. </p> <p>Example of violations: </p> <pre> def a, b = [1, 2] // bad, b is null def c, d, e = [1, 2, 3] // bad, c and d are null class MyClass { def a, b, c = [1, 2, 3] // bad, a and b are null } def x = 1 // ok def (f, g) = [1, 2] // ok (a, b, c) = [1, 2, 3] // ok </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.groovyism.GetterMethodCouldBePropertyRule</key> <severity>MAJOR</severity> <name><![CDATA[Getter Method Could Be Property]]></name> <internalKey><![CDATA[GetterMethodCouldBeProperty]]></internalKey> <description><![CDATA[<p>If a class defines a <code>public</code> method that follows the Java getter notation and that returns a constant, then it is cleaner to provide a Groovy property for the value rather than a Groovy method. </p> <p>Example of violations: </p> <pre> interface Parent { String getSomething() String getSomethingElse() } class Child extends Parent { static VALUE = 'value' @Override String getSomething() { 'something' // this could be simplified } @Override String getSomethingElse() { VALUE // this could be simplified } int getOtherValue() { 123 } static String getName() { 'MyName' } } class Child2 extends Parent { static VALUE = 'value' final String something = 'something' // this is cleaner final String somethingElse = VALUE // this is cleaner final int otherValue = 123 // this is cleaner static final String name = 'MyName' // this is cleaner } </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.groovyism.UseCollectManyRule</key> <severity>MINOR</severity> <name><![CDATA[Use Collect Many]]></name> <internalKey><![CDATA[UseCollectMany]]></internalKey> <description><![CDATA[<p>In many case <code>collectMany()</code> yields the same result as <code>collect{}.flatten()</code>. It is easier to understand and more clearly conveys the intent. </p> <p>Example of violations: </p> <pre> def l = [1, 2, 3, 4] l.collect{ [it, it*2] }.flatten() // suboptimal l.collectMany{ [it, it*2] } // same functionality, better readability </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.groovyism.CollectAllIsDeprecatedRule</key> <severity>MINOR</severity> <name><![CDATA[Collect All Is Deprecated]]></name> <internalKey><![CDATA[CollectAllIsDeprecated]]></internalKey> <description><![CDATA[<p>The <code>collectAll</code> method is deprecated since Groovy 1.8.1. Use <code>collectNested</code> instead. </p> <p>Example of violations: </p> <pre> def list = [1, 2, [3, 4, [5, 6]], 7] list.collectAll { it * 2 } // deprecated list.collectNested { it * 2 } // replacement </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.16 --> <rule> <key>org.codenarc.rule.groovyism.UseCollectNestedRule</key> <severity>MINOR</severity> <name><![CDATA[Use Collect Nested]]></name> <internalKey><![CDATA[UseCollectNested]]></internalKey> <description><![CDATA[<p>Instead of nested <code>collect{}</code> calls use <code>collectNested{}</code>. </p> <p>Example of violations: </p> <pre> def list = [1, 2, [3, 4, 5, 6], [7]] println list.collect { elem -> if (elem instanceof List) elem.collect {it *2} // violation else elem * 2 } println list.collect([8]) { if (it instanceof List) it.collect {it *2} // violation else it * 2 } println list.collectNested { it * 2 } // same functionality, better readability </pre> ]]></description> <tag>groovyism</tag> </rule> <!-- since 0.19 --> <rule> <key>org.codenarc.rule.groovyism.GStringExpressionWithinStringRule</key> <severity>MINOR</severity> <name><![CDATA[G String Expression Within String]]></name> <internalKey><![CDATA[GStringExpressionWithinString]]></internalKey> <description><![CDATA[<p>Check for regular (single quote) strings containing a GString-type expression (${..}). </p> <p>Example of violations: </p> <pre> def str1 = 'total: ${count}' // violation def str2 = 'average: ${total / count}' // violation def str3 = "abc ${count}" // ok; GString def str4 = '$123' // ok def str5 = 'abc {123}' // ok </pre> ]]></description> <tag>groovyism</tag> </rule> </rules>