CodeNarc Report

Report title:Sample Project
Date:Jul 5, 2015 11:33:31 AM
Generated with:CodeNarc v0.23

Summary

PackageTotal FilesFiles with ViolationsPriority 1Priority 2Priority 3
All Packages36335-4731
<Root>93--16
basic44----
braces4----
concurrency26----
convention12----
design232-11
dry4----
exceptions20----
formatting285-91
generic112-21
grails113-5-
groovyism322-15-
imports7----
jdbc6----
junit25----
logging8----
naming167-17
security10----
serialization4----
size103--4
unnecessary464-51
unused74-9-

Package: <Root>

➥ AbstractAstVisitorRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.shouldFailWithM..geContaining

[MSG]Static imports should appear before normal imports

MisorderedStaticImports323

[SRC]import static org.junit.Assert.assertFalse

[MSG]Static imports should appear before normal imports

UnnecessaryObjectReferences3184

[SRC]rule.doNotApplyToClassNames = 'Xxx' // doNotApply = NO

[MSG]The code could be more concise by using a with() or identity() block

UnnecessaryObjectReferences3187

[SRC]rule.applyToClassNames = 'Xxx' // apply = NO

[MSG]The code could be more concise by using a with() or identity() block

UnnecessaryObjectReferences3188

[SRC]rule.doNotApplyToClassNames = 'Xxx' // doNotApply = NO

[MSG]The code could be more concise by using a with() or identity() block

➥ AbstractRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports324

[SRC]import static org.codenarc.test.TestUtil.assertContainsAll

[MSG]Static imports should appear before normal imports

MisorderedStaticImports325

[SRC]import static org.codenarc.test.TestUtil.shouldFailWithM..geContaining

[MSG]Static imports should appear before normal imports

UnnecessaryObjectReferences3127

[SRC]rule.doNotApplyToFilesMatching = NO_MATCH // doNotApply = NO

[MSG]The code could be more concise by using a with() or identity() block

UnnecessaryObjectReferences3130

[SRC]rule.applyToFilesMatching = NO_MATCH // apply = NO

[MSG]The code could be more concise by using a with() or identity() block

UnnecessaryObjectReferences3131

[SRC]rule.doNotApplyToFilesMatching = NO_MATCH // doNotApply = NO

[MSG]The code could be more concise by using a with() or identity() block

UnnecessaryObjectReferences3167

[SRC]rule.applyToFileNames = 'org/codenarc/MyOtherTest.groovy'

[MSG]The code could be more concise by using a with() or identity() block

UnnecessaryObjectReferences3215

[SRC]rule.doNotApplyToFileNames = 'Xxx.groovy' // doNotApply = NO

[MSG]The code could be more concise by using a with() or identity() block

UnnecessaryObjectReferences3218

[SRC]rule.applyToFileNames = 'Xxx.groovy' // apply = NO

[MSG]The code could be more concise by using a with() or identity() block

UnnecessaryObjectReferences3219

[SRC]rule.doNotApplyToFileNames = 'Xxx.groovy' // doNotApply = NO

[MSG]The code could be more concise by using a with() or identity() block

➥ InlineViolationsParserTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports320

[SRC]import static org.codenarc.rule.InlineViolationsParser.inlineViolation

[MSG]Static imports should appear before normal imports

UnnecessaryReturnKeyword3199

[SRC]return [lineNumber: lineNumber, sourceLineText: sourceLi..messageText]

[MSG]The return keyword is not needed and can be removed

Package: design

➥ NestedForLoopRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
UnnecessaryReturnKeyword3105

[SRC]return inlineViolation('Nested for loop')

[MSG]The return keyword is not needed and can be removed

➥ PrivateFieldCouldBeFinalRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MethodCount227

[SRC]class PrivateFieldCouldBeFinalRuleTest extends AbstractRuleTestCase {

[MSG]Class org.codenarc.rule.design.PrivateFieldCouldBeFinalRuleTest has 33 methods

Package: formatting

➥ SpaceAfterClosingBraceRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString239

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { def myMethod() { def closure = { } if (true) { } while(ready) { } try { } catch(Exception e) { } finally { } for(int i=0; i<10; i++) { } for(String name in names) { } for(String name: names) { } if (count > this."maxPriority${priority}Violations") { } while (count > this."maxPriority${priority}Violations") { } } MyClass() { this(classNames) } static void reset() { violationCounts = [1:0, 2:0, 3:0] } void doStuff() { println 9 } } interface MyInterface { } enum MyEnum { OK, BAD } ' contains a GString-type expression: '${priority}Violations") { }'

GStringExpressionWithinString2282

[SRC]assertNoViolations('''

[MSG]The String ' def foo = 1 "I am a ${ -> foo }" ' contains a GString-type expression: '${ -> foo }'

GStringExpressionWithinString2290

[SRC]assertNoViolations('''

[MSG]The String ' def foo = 1 "I am a ${ -> foo }0" ' contains a GString-type expression: '${ -> foo }'

➥ SpaceAfterOpeningBraceRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString239

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { def myMethod() { def closure = { } if (true) { } while(ready) { } try { } catch(Exception e) { } finally { } for(int i=0; i<10; i++) { } for(String name in names) { } for(String name: names) { } if (count > this."maxPriority${priority}Violations") { } while (count > this."maxPriority${priority}Violations") { } } MyClass() { this(classNames) } } interface MyInterface { } enum MyEnum { OK, BAD } trait MyTrait { } ' contains a GString-type expression: '${priority}Violations") { }'

GStringExpressionWithinString279

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { def myMethod() { def closure = {} if (true) {} while(ready) {} try { } catch(Exception e) { } finally {} for(int i=0; i<10; i++) {} for(String name in names) {} for(String name: names) {} if (count > this."maxPriority${priority}Violations") {} while (count > this."maxPriority${priority}Violations") {} } void doStuff2() {} } interface MyInterface2 {} ' contains a GString-type expression: '${priority}Violations") {}'

➥ SpaceAroundMapEntryColonRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
UnnecessaryReturnKeyword3116

[SRC]return inlineViolation("The colon for the literal Map en..className" +

[MSG]The return keyword is not needed and can be removed

➥ SpaceBeforeClosingBraceRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString240

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { def myMethod() { def closure = { } if (true) { } while(ready) { } try { } catch(Exception e) { } finally { } for(int i=0; i<10; i++) { } for(String name in names) { } for(String name: names) { } if (count > this."maxPriority${priority}Violations") { } while (count > this."maxPriority${priority}Violations") { } } MyClass() { this(classNames) } static void reset() { violationCounts = [1:0, 2:0, 3:0] } void doStuff() { println 9 } } interface MyInterface { } enum MyEnum { OK, BAD } ' contains a GString-type expression: '${priority}Violations") { }'

GStringExpressionWithinString281

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { def myMethod() { def closure = {} if (true) {} while(ready) {} try { } catch(Exception e) { } finally {} for(int i=0; i<10; i++) {} for(String name in names) {} for(String name: names) {} if (count > this."maxPriority${priority}Violations") {} while (count > this."maxPriority${priority}Violations") {} } void doStuff2() {} } interface MyInterface2 {} ' contains a GString-type expression: '${priority}Violations") {}'

➥ SpaceBeforeOpeningBraceRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString239

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { def myMethod() { def closure = { } if (true) { } while(ready) { } try { } catch(Exception e) { } finally { } for(int i=0; i<10; i++) { } for(String name in names) { } for(String name: names) { } if (count > this."maxPriority${priority}Violations") { } while (count > this."maxPriority${priority}Violations") { } } MyClass() { this(classNames) } } interface MyInterface { } enum MyEnum { OK, BAD } trait MyTrait { } ' contains a GString-type expression: '${priority}Violations") { }'

GStringExpressionWithinString2255

[SRC]assertNoViolations('''

[MSG]The String ' def foo = 1 "I am a ${ -> foo }" ' contains a GString-type expression: '${ -> foo }'

Package: generic

➥ IllegalPackageReferenceRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString265

[SRC]final SOURCE = '''

[MSG]The String ' if (value.class == org.bad.BadClass) { } println "isClosure=${value instanceof org.bad.OtherClass}" def count = org.bad.Helper.getCount() ' contains a GString-type expression: '${value instanceof org.bad.OtherClass}'

GStringExpressionWithinString273

[SRC][lineNumber:3, sourceLineText:'println "isClosure=${valu..:'org.bad'],

[MSG]The String 'println "isClosure=${value instanceof org.bad.OtherClass}"' contains a GString-type expression: '${value instanceof org.bad.OtherClass}'

➥ RequiredRegexRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.containsAll

[MSG]Static imports should appear before normal imports

Package: grails

➥ GrailsMassAssignmentRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString237

[SRC]final SOURCE = '''

[MSG]The String ' class Person { String name Boolean isAdmin } def bindingMap = [name: 'John', isAdmin: true] def person = new Person() def p2 = new Person("It is currently ${ new Date() }") def p3 = new Person(bindingMap) person.name = bindingMap['name'] person.isAdmin = bindingMap.isAdmin person.properties = "It is currently ${ new Date() }" ' contains a GString-type expression: '${ new Date() }'

➥ GrailsServletContextReferenceRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString279

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { def mySession = servletContext def edit = { println "amount=${servletContext.amount}" } } ' contains a GString-type expression: '${servletContext.amount}'

GStringExpressionWithinString288

[SRC]assertTwoViolations(SOURCE, 3, 'def mySession = servletC..t.amount}"')

[MSG]The String 'println "amount=${servletContext.amount}"' contains a GString-type expression: '${servletContext.amount}'

➥ GrailsSessionReferenceRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString284

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { def mySession = session def edit = { println "amount=${session.amount}" } } ' contains a GString-type expression: '${session.amount}'

GStringExpressionWithinString293

[SRC]assertTwoViolations(SOURCE, 3, 'def mySession = session'..n.amount}"')

[MSG]The String 'println "amount=${session.amount}"' contains a GString-type expression: '${session.amount}'

Package: groovyism

➥ GStringAsMapKeyRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString245

[SRC]final SOURCE = '''

[MSG]The String ' Map map = ["${ someRef }" : 'invalid' ] ' contains a GString-type expression: '${ someRef }'

GStringExpressionWithinString249

[SRC]2, '["${ someRef }" :')

[MSG]The String '["${ someRef }" :' contains a GString-type expression: '${ someRef }'

➥ GStringExpressionWithinStringRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString250

[SRC]final SOURCE = '''

[MSG]The String ' class SomeClass { @SomeAnnotationOnField('${sample.property1}') String sampleProperty @SomeAnnotationOnMethod('${sample.property2}') void method() { } } ' contains a GString-type expression: '${sample.property1}'

GStringExpressionWithinString265

[SRC]final SOURCE = '''

[MSG]The String ' @SomeAnnotationOnClass('${sample.property1}') class SomeClass { @SomeAnnotationOnField('${sample.property2}') String sampleProperty @SomeAnnotationOnMethod('${sample.property3}') void method() { } } ' contains a GString-type expression: '${sample.property1}'

GStringExpressionWithinString281

[SRC]final SOURCE = '''

[MSG]The String ' @SomeAnnotationOnClass(attribute='${sample.property1}', nested=[@NestedAnnotation('${sample.property2}'), @NestedAnnotation('${sample.property3}')], someOtherAttribute='${sample.property4}') class SomeClass { } ' contains a GString-type expression: '${sample.property1}'

GStringExpressionWithinString294

[SRC]final SOURCE = '''

[MSG]The String ' @SomeAnnotationOnClass(attribute=['${sample.property1}', '${sample.property2}']) class SomeClass { } ' contains a GString-type expression: '${sample.property1}', '${sample.property2}'

GStringExpressionWithinString2104

[SRC]final SOURCE = '''

[MSG]The String ' def str1 = "123" def str2 = "abc def ghi" def str3 = "abc ${count}" def str4 = "abc $count }" def str5 = "abc {123}" def str6 = "abc ${}" def str7 = "total: ${count * 25}" ' contains a GString-type expression: '${count}'

GStringExpressionWithinString2118

[SRC]final SOURCE = '''

[MSG]The String ' def str1 = 'total: ${count}' def str2 = 'average: ${total / count}' ' contains a GString-type expression: '${count}'

GStringExpressionWithinString2123

[SRC][lineNumber:2, sourceLineText:"def str1 = 'total: \${cou..{count}\''],

[MSG]The String 'def str1 = 'total: ${count}'' contains a GString-type expression: '${count}'

GStringExpressionWithinString2123

[SRC][lineNumber:2, sourceLineText:"def str1 = 'total: \${cou..{count}\''],

[MSG]The String ''${count}'' contains a GString-type expression: '${count}'

GStringExpressionWithinString2124

[SRC][lineNumber:3, sourceLineText:"def str2 = 'average: \${t.. count}\''])

[MSG]The String 'def str2 = 'average: ${total / count}'' contains a GString-type expression: '${total / count}'

GStringExpressionWithinString2124

[SRC][lineNumber:3, sourceLineText:"def str2 = 'average: \${t.. count}\''])

[MSG]The String ''${total / count}'' contains a GString-type expression: '${total / count}'

GStringExpressionWithinString2129

[SRC]final SOURCE = '''

[MSG]The String ' class SomeClass { @SomeAnnotationOnMethod('${sample.property}') void method() { def str1 = 'total: ${count}' } } ' contains a GString-type expression: '${sample.property}'

GStringExpressionWithinString2137

[SRC]assertSingleViolation(SOURCE, 5, "def str1 = 'total: \${..${count}\'')

[MSG]The String 'def str1 = 'total: ${count}'' contains a GString-type expression: '${count}'

GStringExpressionWithinString2137

[SRC]assertSingleViolation(SOURCE, 5, "def str1 = 'total: \${..${count}\'')

[MSG]The String ''${count}'' contains a GString-type expression: '${count}'

Package: naming

➥ ClassNameRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.shouldFailWithM..geContaining

[MSG]Static imports should appear before normal imports

➥ FieldNameRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MethodCount229

[SRC]class FieldNameRuleTest extends AbstractRuleTestCase {

[MSG]Class org.codenarc.rule.naming.FieldNameRuleTest has 32 methods

MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.shouldFailWithM..geContaining

[MSG]Static imports should appear before normal imports

➥ MethodNameRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.shouldFailWithM..geContaining

[MSG]Static imports should appear before normal imports

➥ PackageNameRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.shouldFailWithM..geContaining

[MSG]Static imports should appear before normal imports

➥ ParameterNameRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.shouldFailWithM..geContaining

[MSG]Static imports should appear before normal imports

➥ PropertyNameRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.shouldFailWithM..geContaining

[MSG]Static imports should appear before normal imports

➥ VariableNameRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.shouldFailWithM..geContaining

[MSG]Static imports should appear before normal imports

Package: size

➥ CrapMetricRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.captureLog4JMessages

[MSG]Static imports should appear before normal imports

➥ GMetricsSourceCodeAdapterTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.shouldFailWithM..geContaining

[MSG]Static imports should appear before normal imports

➥ ParameterCountRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports322

[SRC]import static org.codenarc.test.TestUtil.shouldFail

[MSG]Static imports should appear before normal imports

UnnecessaryReturnKeyword3193

[SRC]return inlineViolation("Number of parameters in ${name} ..ameters}).")

[MSG]The return keyword is not needed and can be removed

Package: unnecessary

➥ ConsecutiveStringConcatenationRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString266

[SRC]final SOURCE = '''

[MSG]The String ' def b = "$Hello" + 'World' // should be "${Hello}World" ' contains a GString-type expression: '${Hello}'

GStringExpressionWithinString274

[SRC]final SOURCE = '''

[MSG]The String ' def c = 'Hello' + "$World" // should be "Hello${World}" ' contains a GString-type expression: '${World}'

➥ UnnecessaryGStringRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString237

[SRC]final SOURCE = '''

[MSG]The String ' def docFile = "src/site/apt/codenarc-rules-${ruleSetName}.apt" ' contains a GString-type expression: '${ruleSetName}'

➥ UnnecessaryPackageReferenceRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString268

[SRC]final SOURCE = '''

[MSG]The String ' if (value.class == java.math.BigDecimal) { } println "isClosure=${value instanceof groovy.lang.Closure}" def processors = java.lang.Runtime.availableProcessors() ' contains a GString-type expression: '${value instanceof groovy.lang.Closure}'

GStringExpressionWithinString275

[SRC][lineNumber:3, sourceLineText:'println "isClosure=${valu..oovy.lang'],

[MSG]The String 'println "isClosure=${value instanceof groovy.lang.Closure}"' contains a GString-type expression: '${value instanceof groovy.lang.Closure}'

➥ UnnecessaryPublicModifierRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MisorderedStaticImports323

[SRC]import static org.codenarc.test.TestUtil.captureLog4JMessages

[MSG]Static imports should appear before normal imports

Package: unused

➥ UnusedMethodParameterRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString2136

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { String myMethod1(String id, int value) { doSomething(value); return id } void myMethod2(int value) { def x = value } def myMethod3(Date startDate) { return "${startDate}" } def myMethod4(Date startDate) { return new Object() { def x = startDate } } def myMethod5(Date startDate) { return new Object() { String toString() { return startDate } } } } ' contains a GString-type expression: '${startDate}" }'

➥ UnusedPrivateFieldRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString2168

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { private int count def other = this."${'count'}" } ' contains a GString-type expression: '${'count'}'

GStringExpressionWithinString2179

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { private int count def varName = "count" def other = this."${varName}" // can't see this } ' contains a GString-type expression: '${varName}'

➥ UnusedPrivateMethodParameterRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString2112

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { private String myMethod1(String id, int value) { doSomething(value); return id } private void myMethod2(int value) { def x = value } private def myMethod3(Date startDate) { return "${startDate}" } private def myMethod4(Date startDate) { return new Object() { def x = startDate } } private def myMethod5(Date startDate) { return new Object() { String toString() { return startDate } } } } ' contains a GString-type expression: '${startDate}" }'

➥ UnusedPrivateMethodRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MethodCount227

[SRC]class UnusedPrivateMethodRuleTest extends AbstractRuleTestCase {

[MSG]Class org.codenarc.rule.unused.UnusedPrivateMethodRuleTest has 32 methods

GStringExpressionWithinString2300

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { private int countStuff() { return 99 } int somePublicMethod() { } def abc = 'abc' private String getName() { 'abc' } private getPrice() { 0.0 } def doStuff() { def count = countStuff() def newName = this.getName() } def myClosure = { println "price is ${getPrice()}" } } ' contains a GString-type expression: '${getPrice()}" }'

GStringExpressionWithinString2369

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { static int getTotal() { println "total=${MyClass.countStuff()}" } private static int countStuff() { } } ' contains a GString-type expression: '${MyClass.countStuff()}'

GStringExpressionWithinString2382

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { private int countStuff() { } def other = this."${countStuff}"() } ' contains a GString-type expression: '${countStuff}'

GStringExpressionWithinString2404

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { private int countStuff() { } def varName = "countStuff" def other = this."${varName}"() // can't see this } ' contains a GString-type expression: '${varName}'

Rule Descriptions

#Rule NameDescription
1AbcMetricChecks the ABC size metric for methods/classes. A method (or "closure field") with an ABC score greater than the maxMethodAbcScore property (60) causes a violation. Likewise, a class that has an (average method) ABC score greater than the maxClassAverageMethodAbcScore property (60) causes a violation.
2AddEmptyStringFinds empty string literals which are being added. This is an inefficient way to convert any type to a String.
3AssertWithinFinallyBlockChecks for assert statements within a finally block. An assert can throw an exception, hiding the original exception, if there is one.
4AssignCollectionSortThe 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.
5AssignCollectionUniqueThe 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.
6AssignmentInConditionalAn assignment operator (=) was used in a conditional test. This is usually a typo, and the comparison operator (==) was intended.
7BigDecimalInstantiationChecks for calls to the BigDecimal constructors that take a double parameter, which may result in an unexpected BigDecimal value.
8BitwiseOperatorInConditionalChecks for bitwise operations in conditionals, if you need to do a bitwise operation then it is best practive to extract a temp variable.
9BooleanGetBooleanThis 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'].
10BrokenNullCheckLooks for faulty checks for null that can cause a NullPointerException.
11BrokenOddnessCheckThe code uses x % 2 == 1 to check to see if a value is odd, but this won't work for negative numbers (e.g., (-5) % 2 == -1). If this code is intending to check for oddness, consider using x & 1 == 1, or x % 2 != 0.
12ClassForNameUsing Class.forName(...) 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.
13ClassSizeChecks if the size of a class exceeds the number of lines specified by the maxLines property (1000).
14ClosureAsLastMethodParameterIf a method is called and the last parameter is an inline closure then it can be declared outside of the method call brackets.
15CollectAllIsDeprecatedcollectAll{} is deprecated since Groovy 1.8.1. Use collectNested instead{}.
16ComparisonOfTwoConstantsChecks for expressions where a comparison operator or equals() or compareTo() is used to compare two constants to each other or two literals that contain only constant values., e.g.: 23 == 67, Boolean.FALSE != false, 0.17 <= 0.99, "abc" > "ddd", [a:1] <=> [a:2], [1,2].equals([3,4]) or [a:false, b:true].compareTo(['a':34.5, b:Boolean.TRUE].
17ComparisonWithSelfChecks for expressions where a comparison operator or equals() or compareTo() is used to compare a variable to itself, e.g.: x == x, x != x, x <=> x, x < x, x =>= x, x.equals(x) or x.compareTo(x), where x is a variable.
18ConfusingMultipleReturnsMultiple 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.
19ConsecutiveLiteralAppendsViolations occur when method calls to append(Object) are chained together with literals as parameters. The chained calls can be joined into one invocation.
20ConsecutiveStringConcatenationCatches concatenation of two string literals on the same line. These can safely by joined.
21ConstantAssertExpressionChecks for assert statements where the assert boolean condition expression is a constant or literal value.
22ConstantIfExpressionChecks for if statements with a constant value for the if expression, such as true, false, null, or a literal constant value.
23ConstantTernaryExpressionChecks for ternary expressions with a constant value for the boolean expression, such as true, false, null, or a literal constant value.
24CrapMetricChecks the CRAP (Change Risk Anti-Patterns) score for methods/classes. 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 maxMethodCrapScore property (30) causes a violation. Likewise, a class that has an (average method) CRAP value greater than the maxClassAverageMethodCrapScore property (30) causes a violation.
25CyclomaticComplexityChecks the cyclomatic complexity for methods/classes.A method (or "closure field") with a cyclomatic complexity value greater than the maxMethodComplexity property (20) causes a violation. Likewise, a class that has an (average method) cyclomatic complexityvalue greater than the maxClassAverageMethodComplexity property (20) causes a violation.
26DeadCodeDead code appears after a return 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.
27DoubleNegativeThere is no point in using a double negative, it is always positive. For instance !!x can always be simplified to x. And !(!x) can as well.
28DuplicateCaseStatementCheck for duplicate case statements in a switch block, such as two equal integers or strings.
29DuplicateImportDuplicate import statements are unnecessary.
30DuplicateMapKeyA map literal is created with duplicated key. The map entry will be overwritten.
31DuplicateSetValueA Set literal is created with duplicate constant value. A set cannot contain two elements with the same value.
32EmptyCatchBlockIn most cases, exceptions should not be caught and ignored (swallowed).
33EmptyClassReports classes without methods, fields or properties. Why would you need a class like this?
34EmptyElseBlockEmpty else blocks are confusing and serve no purpose.
35EmptyFinallyBlockEmpty finally blocks are confusing and serve no purpose.
36EmptyForStatementEmpty for statements are confusing and serve no purpose.
37EmptyIfStatementEmpty if statements are confusing and serve no purpose.
38EmptyInstanceInitializerAn empty class instance initializer was found. It is safe to remove it.
39EmptyMethodA method was found without an implementation. If the method is overriding or implementing a parent method, then mark it with the @Override annotation.
40EmptyStaticInitializerAn empty static initializer was found. It is safe to remove it.
41EmptySwitchStatementEmpty switch statements are confusing and serve no purpose.
42EmptySynchronizedStatementEmpty synchronized statements are confusing and serve no purpose.
43EmptyTryBlockEmpty try blocks are confusing and serve no purpose.
44EmptyWhileStatementEmpty while statements are confusing and serve no purpose.
45EqualsAndHashCodeIf either the boolean equals(Object) or the int hashCode() methods are overridden within a class, then both must be overridden.
46EqualsOverloadedThe class has an equals method, but the parameter of the method is not of type Object. It is not overriding equals but instead overloading it.
47ExplicitArrayListInstantiationThis rule checks for the explicit instantiation of an ArrayList using the no-arg constructor. In Groovy, it is best to write new ArrayList() as [], which creates the same object.
48ExplicitCallToAndMethodThis rule detects when the and(Object) method is called directly in code instead of using the & operator. A groovier way to express this: a.and(b) is this: a & b
49ExplicitCallToCompareToMethodThis rule detects when the compareTo(Object) method is called directly in code instead of using the <=>, >, >=, <, and <= operators. A groovier way to express this: a.compareTo(b) is this: a <=> b, or using the other operators.
50ExplicitCallToDivMethodThis rule detects when the div(Object) method is called directly in code instead of using the / operator. A groovier way to express this: a.div(b) is this: a / b
51ExplicitCallToEqualsMethodThis rule detects when the equals(Object) method is called directly in code instead of using the == or != operator. A groovier way to express this: a.equals(b) is this: a == b and a groovier way to express : !a.equals(b) is : a != b
52ExplicitCallToGetAtMethodThis rule detects when the getAt(Object) method is called directly in code instead of using the [] index operator. A groovier way to express this: a.getAt(b) is this: a[b]
53ExplicitCallToLeftShiftMethodThis rule detects when the leftShift(Object) method is called directly in code instead of using the << operator. A groovier way to express this: a.leftShift(b) is this: a << b
54ExplicitCallToMinusMethodThis rule detects when the minus(Object) method is called directly in code instead of using the - operator. A groovier way to express this: a.minus(b) is this: a - b
55ExplicitCallToModMethodThis rule detects when the mod(Object) method is called directly in code instead of using the % operator. A groovier way to express this: a.mod(b) is this: a % b
56ExplicitCallToMultiplyMethodThis rule detects when the minus(Object) method is called directly in code instead of using the * operator. A groovier way to express this: a.multiply(b) is this: a * b
57ExplicitCallToOrMethodThis rule detects when the or(Object) method is called directly in code instead of using the | operator. A groovier way to express this: a.or(b) is this: a | b
58ExplicitCallToPlusMethodThis rule detects when the plus(Object) method is called directly in code instead of using the + operator. A groovier way to express this: a.plus(b) is this: a + b
59ExplicitCallToPowerMethodThis rule detects when the power(Object) method is called directly in code instead of using the ** operator. A groovier way to express this: a.power(b) is this: a ** b
60ExplicitCallToRightShiftMethodThis rule detects when the rightShift(Object) method is called directly in code instead of using the >> operator. A groovier way to express this: a.rightShift(b) is this: a >> b
61ExplicitCallToXorMethodThis rule detects when the xor(Object) method is called directly in code instead of using the ^ operator. A groovier way to express this: a.xor(b) is this: a ^ b
62ExplicitGarbageCollectionCalls to System.gc(), Runtime.getRuntime().gc(), and System.runFinalization() are not advised. Code should have the same behavior whether the garbage collection is disabled using the option -Xdisableexplicitgc or not. Moreover, "modern" jvms do a very good job handling garbage collections. If memory usage issues unrelated to memory leaks develop within an application, it should be dealt with JVM options rather than within the code itself.
63ExplicitHashMapInstantiationThis rule checks for the explicit instantiation of a HashMap using the no-arg constructor. In Groovy, it is best to write new HashMap() as [:], which creates the same object.
64ExplicitHashSetInstantiationThis rule checks for the explicit instantiation of a HashSet using the no-arg constructor. In Groovy, it is best to write new HashSet() as [] as Set, which creates the same object.
65ExplicitLinkedHashMapInstantiationThis rule checks for the explicit instantiation of a LinkedHashMap using the no-arg constructor. In Groovy, it is best to write new LinkedHashMap() as [:], which creates the same object.
66ExplicitLinkedListInstantiationThis rule checks for the explicit instantiation of a LinkedList using the no-arg constructor. In Groovy, it is best to write new LinkedList() as [] as Queue, which creates the same object.
67ExplicitStackInstantiationThis rule checks for the explicit instantiation of a Stack using the no-arg constructor. In Groovy, it is best to write new Stack() as [] as Stack, which creates the same object.
68ExplicitTreeSetInstantiationThis rule checks for the explicit instantiation of a TreeSet using the no-arg constructor. In Groovy, it is best to write new TreeSet() as [] as SortedSet, which creates the same object.
69ForLoopShouldBeWhileLoopA for loop without an init and update statement can be simplified to a while loop.
70GStringAsMapKeyA GString should not be used as a map key since its hashcode is not guaranteed to be stable. Consider calling key.toString().
71GStringExpressionWithinStringCheck for regular (single quote) strings containing a GString-type expression (${...}).
72GetterMethodCouldBePropertyIf a class defines a public method that follows the Java getter notation, and returns a constant, then it is cleaner to provide a Groovy property for the value rather than a Groovy method.
73GroovyLangImmutableThe groovy.lang.Immutable annotation has been deprecated and replaced by groovy.transform.Immutable. Do not use the Immutable in groovy.lang.
74HardCodedWindowsFileSeparatorThis 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.
75HardCodedWindowsRootDirectoryThis rule find cases where a File object is constructed with a windows-based path. This is not portable, and using the File.listRoots() method is a better alternative.
76ImportFromSamePackageAn import of a class that is within the same package is unnecessary.
77ImportFromSunPackagesAvoid importing anything from the 'sun.*' packages. These packages are not portable and are likely to change.
78IntegerGetIntegerThis 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'].
79MethodCountA 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.The maxMethods property (30) specifies the threshold.
80MethodSizeChecks if the size of a method exceeds the number of lines specified by the maxLines property (100).
81MisorderedStaticImportsStatic imports should never be declared after nonstatic imports.
82MultipleUnaryOperatorsChecks for multiple consecutive unary operators. These are confusing, and are likely typos and bugs.
83NestedBlockDepthChecks for blocks or closures nested more than maxNestedBlockDepth (5) levels deep.
84NoWildcardImportsWildcard imports, static or otherwise, should not be used.
85ParameterCountChecks if the number of parameters in method/constructor exceeds the number of parameters specified by the maxParameters property.
86RandomDoubleCoercedToZeroThe 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 or int, then it is coerced to zero. Casting the result to int, or assigning it to an int field is probably a bug.
87RemoveAllOnSelfDon't use removeAll to clear a collection. If you want to remove all elements from a collection c, use c.clear, not c.removeAll(c). Calling c.removeAll(c) to clear a collection is less clear, susceptible to errors from typos, less efficient and for some collections, might throw a ConcurrentModificationException.
88ReturnFromFinallyBlockReturning from a finally block is confusing and can hide the original exception.
89ThrowExceptionFromFinallyBlockThrowing an exception from a finally block is confusing and can hide the original exception.
90UnnecessaryBigDecimalInstantiationIt is unnecessary to instantiate BigDecimal objects. Instead just use the decimal literal or the 'G' identifier to force the type, such as 123.45 or 123.45G.
91UnnecessaryBigIntegerInstantiationIt is unnecessary to instantiate BigInteger objects. Instead just use the literal with the 'G' identifier to force the type, such as 8G or 42G.
92UnnecessaryBooleanExpressionChecks for unnecessary boolean expressions, including ANDing (&&) or ORing (||) with true, false, null, or a Map/List/String/Number literal. Also checks for negation (!) of true, false, null, or a Map/List/String/Number literal.
93UnnecessaryBooleanInstantiationUse Boolean.valueOf() for variable values or Boolean.TRUE and Boolean.FALSE for constant values instead of calling the Boolean() constructor directly or calling Boolean.valueOf(true) or Boolean.valueOf(false).
94UnnecessaryCallForLastElementThis 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 array[array.length - 1], in Groovy it is simpler to either call array.last() or array[-1]. The same is true for lists. This violation is triggered whenever a get, getAt, or array-style access is used with an object size check.
95UnnecessaryCallToSubstringCalling String.substring(0) always returns the original string. This code is meaningless.
96UnnecessaryCastChecks for unnecessary cast operations
97UnnecessaryCatchBlockViolations 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 catch statement out.
98UnnecessaryCollectCallSome method calls to Object.collect(Closure) can be replaced with the spread operator. For instance, list.collect { it.multiply(2) } can be replaced by list*.multiply(2). Warning: if a collection is null, collect will return an empty list, while *. will return null.
99UnnecessaryCollectionCallUseless call to collections. This call doesn't make sense. For any collection c, calling c.containsAll(c) should always be true, and c.retainAll(c) should have no effect.
100UnnecessaryConstructorThis rule detects when a constructor is not necessary; i.e., when there's only one constructor, it's public, has an empty body, and takes no arguments.
101UnnecessaryDefInFieldDeclarationIf 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 = {}.
102UnnecessaryDefInMethodDeclarationIf 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() {}'.
103UnnecessaryDefInVariableDeclarationIf 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'.
104UnnecessaryDotClassTo make a reference to a class, it is unnecessary to specify the '.class' identifier. For instance String.class can be shortened to String.
105UnnecessaryDoubleInstantiationIt is unnecessary to instantiate Double objects. Instead just use the double literal or the 'D' identifier to force the type, such as 123.45d or 0.42d.
106UnnecessaryElseStatementWhen an if statement block ends with a return statement the else is unnecessary. The logic in the else branch can be run without being in a new scope.
107UnnecessaryFinalOnPrivateMethodA private method is marked final. Private methods cannot be overridden, so marking it final is unnecessary.
108UnnecessaryFloatInstantiationIt is unnecessary to instantiate Float objects. Instead just use the float literal with the 'F' identifier to force the type, such as 123.45F or 0.42f.
109UnnecessaryGStringString 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.
110UnnecessaryGroovyImportA 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.
111UnnecessaryIfStatementChecks for if statements where the if and else blocks (or subsequent fall-through to a return) are merely returning true and false constants. These cases can be replaced by a simple return statement.
112UnnecessaryInstanceOfCheckThis rule finds instanceof checks that cannot possibly evaluate to true. For instance, checking that (!variable instanceof String) will never be true because the result of a not expression is always a boolean.
113UnnecessaryInstantiationToGetClassAvoid instantiating an object just to call getClass() on it; use the .class public member instead.
114UnnecessaryIntegerInstantiationIt is unnecessary to instantiate Integer objects. Instead just use the literal with the 'I' identifier to force the type, such as 8I or 42i.
115UnnecessaryLongInstantiationIt is unnecessary to instantiate Long objects. Instead just use the literal with the 'L' identifier to force the type, such as 8L or 42L.
116UnnecessaryModOneAny 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).
117UnnecessaryNullCheckGroovy contains the safe dereference operator, which can be used in boolean conditional statements to safely replace explicit "x == null" tests.
118UnnecessaryNullCheckBeforeInstanceOfThere is no need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.
119UnnecessaryObjectReferencesViolations are triggered when an excessive set of consecutive statements all reference the same variable. This can be made more readable by using a with or identity block.
120UnnecessaryOverridingMethodThe overriding method merely calls the same method defined in a superclass
121UnnecessaryPackageReferenceChecks for explicit package reference for classes that Groovy imports by default, such as java.lang.String, java.util.Map and groovy.lang.Closure.
122UnnecessaryParenthesesForMethodCallWithClosureIf 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.
123UnnecessaryPublicModifierThe 'public' modifier is not required on methods or classes.
124UnnecessaryReturnKeywordIn Groovy, the return keyword is often optional. If a statement is the last line in a method or closure then you do not need to have the return keyword.
125UnnecessarySafeNavigationOperatorCheck for the safe navigation operator (?.) applied to constants and literals, which can never be null.
126UnnecessarySelfAssignmentMethod contains a pointless self-assignment to a variable or property.
127UnnecessarySemicolonSemicolons 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.
128UnnecessaryStringInstantiationUse a String literal (e.g., "...") instead of calling the corresponding String constructor (new String("..")) directly.
129UnnecessarySubstringThis rule finds usages of String.substring(int) and String.substring(int, int) that can be replaced by use of the subscript operator. For instance, var.substring(5) can be replaced with var[5..-1].
130UnnecessaryTernaryExpressionChecks for ternary expressions where the conditional expression always evaluates to a boolean and the true and false expressions are merely returning true and false constants. Also checks for ternary expressions where both expressions are the same constant or variable.
131UnnecessaryToStringChecks for unnecessary calls to toString().
132UnnecessaryTransientModifierThe field is marked as transient, but the class isn't Serializable, so marking it as transient has no effect.
133UnusedImportImports for a class that is never referenced within the source file is unnecessary.
134UseCollectManyIn many case collectMany() yields the same result as collect{}.flatten(). It is easier to understand and more clearly conveys the intent.
135UseCollectNestedInstead of nested collect{}-calls use collectNested{}