From 70cf69feb403ac9464c49f72b19fee939ffe1cb3 Mon Sep 17 00:00:00 2001 From: Chris Mair Date: Sat, 9 Sep 2017 13:04:15 -0400 Subject: [PATCH] v1.0 --- src/site/apt/codenarc-rules-convention.apt | 2 +- .../resources/SampleCodeNarcHtmlReport.html | 24 +++++-------- .../SampleCodeNarcSortableHtmlReport.html | 20 ++++------- .../resources/SampleCodeNarcTextReport.txt | 34 +++++-------------- .../resources/SampleCodeNarcXmlReport.xml | 26 +++++--------- 5 files changed, 32 insertions(+), 74 deletions(-) diff --git a/src/site/apt/codenarc-rules-convention.apt b/src/site/apt/codenarc-rules-convention.apt index f37ea5a0f..f6266ef20 100644 --- a/src/site/apt/codenarc-rules-convention.apt +++ b/src/site/apt/codenarc-rules-convention.apt @@ -60,7 +60,7 @@ Convention Rules ("") * {CouldBeSwitchStatement} Rule ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - + Checks for three of more if statements that could be converted to a switch. Only applies to equality and instanceof. diff --git a/src/site/resources/SampleCodeNarcHtmlReport.html b/src/site/resources/SampleCodeNarcHtmlReport.html index 34203162b..ca75dbacf 100644 --- a/src/site/resources/SampleCodeNarcHtmlReport.html +++ b/src/site/resources/SampleCodeNarcHtmlReport.html @@ -161,7 +161,7 @@ em, .em { font-weight: bold; -}

CodeNarc Report

Summary

PackageTotal FilesFiles with ViolationsPriority 1Priority 2Priority 3
All Packages36540-5431
<Root>93--16
basic44----
braces4----
concurrency26----
convention14----
design232-11
dry4----
exceptions20----
formatting288-121
generic112-21
grails113-5-
groovyism322-16-
imports71-1-
jdbc6----
junit25----
logging8----
naming167-17
security10----
serialization4----
size103--4
unnecessary464-51
unused75-11-

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

UnnecessaryObjectReferences3137

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

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

UnnecessaryObjectReferences3140

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

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

UnnecessaryObjectReferences3141

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

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

UnnecessaryObjectReferences3177

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

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

UnnecessaryObjectReferences3225

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

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

UnnecessaryObjectReferences3228

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

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

UnnecessaryObjectReferences3229

[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

➥ BracesForForLoopRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString2102

[SRC]final SOURCE = '''

[MSG]The String ' +}

CodeNarc Report

Summary

PackageTotal FilesFiles with ViolationsPriority 1Priority 2Priority 3
All Packages36537-5229
<Root>93--16
basic44----
braces4----
concurrency26----
convention15----
design232-11
dry4----
exceptions20----
formatting288-121
generic112-21
grails102-3-
groovyism322-16-
imports71-1-
jdbc6----
junit25----
logging8----
naming167-17
security10----
serialization4----
size92--3
unnecessary473-5-
unused75-11-

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

UnnecessaryObjectReferences3137

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

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

UnnecessaryObjectReferences3140

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

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

UnnecessaryObjectReferences3141

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

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

UnnecessaryObjectReferences3177

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

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

UnnecessaryObjectReferences3225

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

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

UnnecessaryObjectReferences3228

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

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

UnnecessaryObjectReferences3229

[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

➥ BracesForForLoopRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString2102

[SRC]final SOURCE = '''

[MSG]The String ' for(String name=${SomeClass.SOME_CONSTANT}; name==null;) // And what about {} { doStuff() @@ -201,10 +201,10 @@ } interface MyInterface { } enum MyEnum { OK, BAD } - ' contains a GString-type expression: '${priority}Violations") { }'

GStringExpressionWithinString2282

[SRC]assertNoViolations('''

[MSG]The String ' + ' contains a GString-type expression: '${priority}Violations") { }'

GStringExpressionWithinString2293

[SRC]assertNoViolations('''

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

GStringExpressionWithinString2290

[SRC]assertNoViolations('''

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

GStringExpressionWithinString2301

[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 ' @@ -337,15 +337,7 @@ 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 ' + ' 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}'

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 { @@ -441,7 +433,7 @@ def OPERATORS2 = 9*TestData10.VALUE/TestData11.VALUE def OPERATORS3 = 64&TestData12.VALUE|TestData13.VALUE^TestData14.VALUE def OPERATORS4 = !TestData15.VALUE - ' contains a GString-type expression: '${TestData1.GOOD_XML}'

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 ' + ' contains a GString-type expression: '${TestData1.GOOD_XML}'

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

➥ 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

UnnecessaryReturnKeyword3253

[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}" @@ -451,7 +443,7 @@ 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 ' + ' 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}'

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 } @@ -467,7 +459,7 @@ } } } - ' contains a GString-type expression: '${startDate}" }'

➥ UnusedPrivateFieldRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MethodCount229

[SRC]class UnusedPrivateFieldRuleTest extends AbstractRuleTestCase {

[MSG]Class org.codenarc.rule.unused.UnusedPrivateFieldRuleTest has 31 methods

GStringExpressionWithinString2168

[SRC]final SOURCE = '''

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

➥ UnusedPrivateFieldRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MethodCount229

[SRC]class UnusedPrivateFieldRuleTest extends AbstractRuleTestCase {

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

GStringExpressionWithinString2168

[SRC]final SOURCE = '''

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

➥ UnusedVariableRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MethodCount227

[SRC]class UnusedVariableRuleTest extends AbstractRuleTestCase {

[MSG]Class org.codenarc.rule.unused.UnusedVariableRuleTest has 34 methods

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{}
\ No newline at end of file + ' contains a GString-type expression: '${varName}'

➥ UnusedVariableRuleTest.groovy

Rule NamePriorityLine #Source Line / Message
MethodCount227

[SRC]class UnusedVariableRuleTest extends AbstractRuleTestCase {

[MSG]Class org.codenarc.rule.unused.UnusedVariableRuleTest has 35 methods

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.
128UnnecessarySetterChecks for explicit calls to setter methods which can, for the most part, be replaced by assignment to property. A setter is defined as a method call that matches set[A-Z] but not set[A-Z][A-Z] such as setURL(). Setters take one method argument.
129UnnecessaryStringInstantiationUse a String literal (e.g., "...") instead of calling the corresponding String constructor (new String("..")) directly.
130UnnecessarySubstringThis 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].
131UnnecessaryTernaryExpressionChecks 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.
132UnnecessaryToStringChecks for unnecessary calls to toString().
133UnnecessaryTransientModifierThe field is marked as transient, but the class isn't Serializable, so marking it as transient has no effect.
134UnusedImportImports for a class that is never referenced within the source file is unnecessary.
135UseCollectManyIn many case collectMany() yields the same result as collect{}.flatten(). It is easier to understand and more clearly conveys the intent.
136UseCollectNestedInstead of nested collect{}-calls use collectNested{}
\ No newline at end of file diff --git a/src/site/resources/SampleCodeNarcSortableHtmlReport.html b/src/site/resources/SampleCodeNarcSortableHtmlReport.html index af4f8e9a4..4dcee9c8a 100644 --- a/src/site/resources/SampleCodeNarcSortableHtmlReport.html +++ b/src/site/resources/SampleCodeNarcSortableHtmlReport.html @@ -255,7 +255,7 @@ } } } - }

CodeNarc Report

Summary

Total FilesFiles with ViolationsPriority 1Priority 2Priority 3
36540-5431

Violations

FileRule NamePriorityLine #Source Line / Message
design/PrivateFieldCouldBeFinalRuleTest.groovyMethodCount227

[SRC]class PrivateFieldCouldBeFinalRuleTest extends AbstractRuleTestCase {

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

formatting/BracesForForLoopRuleTest.groovyGStringExpressionWithinString2102

[SRC]final SOURCE = '''

[MSG]The String ' + }

CodeNarc Report

Summary

Total FilesFiles with ViolationsPriority 1Priority 2Priority 3
36537-5229

Violations

FileRule NamePriorityLine #Source Line / Message
design/PrivateFieldCouldBeFinalRuleTest.groovyMethodCount227

[SRC]class PrivateFieldCouldBeFinalRuleTest extends AbstractRuleTestCase {

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

formatting/BracesForForLoopRuleTest.groovyGStringExpressionWithinString2102

[SRC]final SOURCE = '''

[MSG]The String ' for(String name=${SomeClass.SOME_CONSTANT}; name==null;) // And what about {} { doStuff() @@ -295,10 +295,10 @@ } interface MyInterface { } enum MyEnum { OK, BAD } - ' contains a GString-type expression: '${priority}Violations") { }'

formatting/SpaceAfterClosingBraceRuleTest.groovyGStringExpressionWithinString2282

[SRC]assertNoViolations('''

[MSG]The String ' + ' contains a GString-type expression: '${priority}Violations") { }'

formatting/SpaceAfterClosingBraceRuleTest.groovyGStringExpressionWithinString2293

[SRC]assertNoViolations('''

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

formatting/SpaceAfterClosingBraceRuleTest.groovyGStringExpressionWithinString2290

[SRC]assertNoViolations('''

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

formatting/SpaceAfterClosingBraceRuleTest.groovyGStringExpressionWithinString2301

[SRC]assertNoViolations('''

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

formatting/SpaceAfterOpeningBraceRuleTest.groovyGStringExpressionWithinString239

[SRC]final SOURCE = '''

[MSG]The String ' @@ -431,15 +431,7 @@ println "amount=${servletContext.amount}" } } - ' contains a GString-type expression: '${servletContext.amount}'

grails/GrailsServletContextReferenceRuleTest.groovyGStringExpressionWithinString288

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

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

grails/GrailsSessionReferenceRuleTest.groovyGStringExpressionWithinString284

[SRC]final SOURCE = '''

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

grails/GrailsSessionReferenceRuleTest.groovyGStringExpressionWithinString293

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

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

groovyism/GStringAsMapKeyRuleTest.groovyGStringExpressionWithinString245

[SRC]final SOURCE = '''

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

grails/GrailsServletContextReferenceRuleTest.groovyGStringExpressionWithinString288

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

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

groovyism/GStringAsMapKeyRuleTest.groovyGStringExpressionWithinString245

[SRC]final SOURCE = '''

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

groovyism/GStringAsMapKeyRuleTest.groovyGStringExpressionWithinString249

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

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString250

[SRC]final SOURCE = '''

[MSG]The String ' class SomeClass { @@ -561,7 +553,7 @@ } } } - ' contains a GString-type expression: '${startDate}" }'

unused/UnusedPrivateFieldRuleTest.groovyMethodCount229

[SRC]class UnusedPrivateFieldRuleTest extends AbstractRuleTestCase {

[MSG]Class org.codenarc.rule.unused.UnusedPrivateFieldRuleTest has 31 methods

unused/UnusedPrivateFieldRuleTest.groovyGStringExpressionWithinString2168

[SRC]final SOURCE = '''

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

unused/UnusedPrivateFieldRuleTest.groovyMethodCount229

[SRC]class UnusedPrivateFieldRuleTest extends AbstractRuleTestCase {

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

unused/UnusedPrivateFieldRuleTest.groovyGStringExpressionWithinString2168

[SRC]final SOURCE = '''

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

unused/UnusedVariableRuleTest.groovyMethodCount227

[SRC]class UnusedVariableRuleTest extends AbstractRuleTestCase {

[MSG]Class org.codenarc.rule.unused.UnusedVariableRuleTest has 34 methods

AbstractAstVisitorRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

AbstractAstVisitorRuleTest.groovyMisorderedStaticImports323

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

[MSG]Static imports should appear before normal imports

AbstractAstVisitorRuleTest.groovyUnnecessaryObjectReferences3184

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

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

AbstractAstVisitorRuleTest.groovyUnnecessaryObjectReferences3187

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

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

AbstractAstVisitorRuleTest.groovyUnnecessaryObjectReferences3188

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

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

AbstractRuleTest.groovyMisorderedStaticImports324

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

[MSG]Static imports should appear before normal imports

AbstractRuleTest.groovyMisorderedStaticImports325

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

[MSG]Static imports should appear before normal imports

AbstractRuleTest.groovyUnnecessaryObjectReferences3137

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3140

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3141

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3177

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3225

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3228

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3229

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

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

InlineViolationsParserTest.groovyMisorderedStaticImports320

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

[MSG]Static imports should appear before normal imports

InlineViolationsParserTest.groovyUnnecessaryReturnKeyword3199

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

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

design/NestedForLoopRuleTest.groovyUnnecessaryReturnKeyword3105

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

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

formatting/SpaceAroundMapEntryColonRuleTest.groovyUnnecessaryReturnKeyword3116

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

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

generic/RequiredRegexRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/ClassNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/FieldNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/MethodNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/PackageNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/ParameterNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/PropertyNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/VariableNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

size/CrapMetricRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

size/GMetricsSourceCodeAdapterTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

size/ParameterCountRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

size/ParameterCountRuleTest.groovyUnnecessaryReturnKeyword3193

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

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

unnecessary/UnnecessaryPublicModifierRuleTest.groovyMisorderedStaticImports323

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

[MSG]Static imports should appear before normal imports

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{}
\ No newline at end of file + ' contains a GString-type expression: '${varName}'

unused/UnusedVariableRuleTest.groovyMethodCount227

[SRC]class UnusedVariableRuleTest extends AbstractRuleTestCase {

[MSG]Class org.codenarc.rule.unused.UnusedVariableRuleTest has 35 methods

AbstractAstVisitorRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

AbstractAstVisitorRuleTest.groovyMisorderedStaticImports323

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

[MSG]Static imports should appear before normal imports

AbstractAstVisitorRuleTest.groovyUnnecessaryObjectReferences3184

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

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

AbstractAstVisitorRuleTest.groovyUnnecessaryObjectReferences3187

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

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

AbstractAstVisitorRuleTest.groovyUnnecessaryObjectReferences3188

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

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

AbstractRuleTest.groovyMisorderedStaticImports324

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

[MSG]Static imports should appear before normal imports

AbstractRuleTest.groovyMisorderedStaticImports325

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

[MSG]Static imports should appear before normal imports

AbstractRuleTest.groovyUnnecessaryObjectReferences3137

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3140

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3141

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3177

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3225

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3228

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

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

AbstractRuleTest.groovyUnnecessaryObjectReferences3229

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

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

InlineViolationsParserTest.groovyMisorderedStaticImports320

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

[MSG]Static imports should appear before normal imports

InlineViolationsParserTest.groovyUnnecessaryReturnKeyword3199

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

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

design/NestedForLoopRuleTest.groovyUnnecessaryReturnKeyword3105

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

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

formatting/SpaceAroundMapEntryColonRuleTest.groovyUnnecessaryReturnKeyword3116

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

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

generic/RequiredRegexRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/ClassNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/FieldNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/MethodNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/PackageNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/ParameterNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/PropertyNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

naming/VariableNameRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

size/GMetricsSourceCodeAdapterTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

size/ParameterCountRuleTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

size/ParameterCountRuleTest.groovyUnnecessaryReturnKeyword3253

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

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

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.
128UnnecessarySetterChecks for explicit calls to setter methods which can, for the most part, be replaced by assignment to property. A setter is defined as a method call that matches set[A-Z] but not set[A-Z][A-Z] such as setURL(). Setters take one method argument.
129UnnecessaryStringInstantiationUse a String literal (e.g., "...") instead of calling the corresponding String constructor (new String("..")) directly.
130UnnecessarySubstringThis 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].
131UnnecessaryTernaryExpressionChecks 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.
132UnnecessaryToStringChecks for unnecessary calls to toString().
133UnnecessaryTransientModifierThe field is marked as transient, but the class isn't Serializable, so marking it as transient has no effect.
134UnusedImportImports for a class that is never referenced within the source file is unnecessary.
135UseCollectManyIn many case collectMany() yields the same result as collect{}.flatten(). It is easier to understand and more clearly conveys the intent.
136UseCollectNestedInstead of nested collect{}-calls use collectNested{}
\ No newline at end of file diff --git a/src/site/resources/SampleCodeNarcTextReport.txt b/src/site/resources/SampleCodeNarcTextReport.txt index 2b95984a7..6783de07e 100644 --- a/src/site/resources/SampleCodeNarcTextReport.txt +++ b/src/site/resources/SampleCodeNarcTextReport.txt @@ -1,6 +1,6 @@ -CodeNarc Report: Sample Project - Mar 18, 2017 10:39:06 AM +CodeNarc Report: Sample Project - Sep 9, 2017 12:34:41 PM -Summary: TotalFiles=365 FilesWithViolations=40 P1=0 P2=54 P3=31 +Summary: TotalFiles=365 FilesWithViolations=37 P1=0 P2=52 P3=29 File: AbstractAstVisitorRuleTest.groovy Violation: Rule=MisorderedStaticImports P=3 Line=22 Msg=[Static imports should appear before normal imports] Src=[import static org.codenarc.test.TestUtil.shouldFailWithMessageContaining] @@ -81,11 +81,11 @@ File: formatting/SpaceAfterClosingBraceRuleTest.groovy interface MyInterface { } enum MyEnum { OK, BAD } ' contains a GString-type expression: '${priority}Violations") { }'] Src=[final SOURCE = '''] - Violation: Rule=GStringExpressionWithinString P=2 Line=282 Msg=[The String ' + Violation: Rule=GStringExpressionWithinString P=2 Line=293 Msg=[The String ' def foo = 1 "I am a ${ -> foo }" ' contains a GString-type expression: '${ -> foo }'] Src=[assertNoViolations('''] - Violation: Rule=GStringExpressionWithinString P=2 Line=290 Msg=[The String ' + Violation: Rule=GStringExpressionWithinString P=2 Line=301 Msg=[The String ' def foo = 1 "I am a ${ -> foo }0" ' contains a GString-type expression: '${ -> foo }'] Src=[assertNoViolations('''] @@ -249,18 +249,6 @@ File: grails/GrailsServletContextReferenceRuleTest.groovy ' contains a GString-type expression: '${servletContext.amount}'] Src=[final SOURCE = '''] Violation: Rule=GStringExpressionWithinString P=2 Line=88 Msg=[The String 'println "amount=${servletContext.amount}"' contains a GString-type expression: '${servletContext.amount}'] Src=[assertTwoViolations(SOURCE, 3, 'def mySession = servletContext', 6, 'println "amount=${servletContext.amount}"')] -File: grails/GrailsSessionReferenceRuleTest.groovy - Violation: Rule=GStringExpressionWithinString P=2 Line=84 Msg=[The String ' - class MyClass { - def mySession = session - - def edit = { - println "amount=${session.amount}" - } - } - ' contains a GString-type expression: '${session.amount}'] Src=[final SOURCE = '''] - Violation: Rule=GStringExpressionWithinString P=2 Line=93 Msg=[The String 'println "amount=${session.amount}"' contains a GString-type expression: '${session.amount}'] Src=[assertTwoViolations(SOURCE, 3, 'def mySession = session', 6, 'println "amount=${session.amount}"')] - File: groovyism/GStringAsMapKeyRuleTest.groovy Violation: Rule=GStringExpressionWithinString P=2 Line=45 Msg=[The String ' Map map = ["${ someRef }" : 'invalid' ] @@ -402,15 +390,12 @@ File: naming/PropertyNameRuleTest.groovy File: naming/VariableNameRuleTest.groovy Violation: Rule=MisorderedStaticImports P=3 Line=22 Msg=[Static imports should appear before normal imports] Src=[import static org.codenarc.test.TestUtil.shouldFailWithMessageContaining] -File: size/CrapMetricRuleTest.groovy - Violation: Rule=MisorderedStaticImports P=3 Line=22 Msg=[Static imports should appear before normal imports] Src=[import static org.codenarc.test.TestUtil.captureLog4JMessages] - File: size/GMetricsSourceCodeAdapterTest.groovy Violation: Rule=MisorderedStaticImports P=3 Line=22 Msg=[Static imports should appear before normal imports] Src=[import static org.codenarc.test.TestUtil.shouldFailWithMessageContaining] File: size/ParameterCountRuleTest.groovy Violation: Rule=MisorderedStaticImports P=3 Line=22 Msg=[Static imports should appear before normal imports] Src=[import static org.codenarc.test.TestUtil.shouldFail] - Violation: Rule=UnnecessaryReturnKeyword P=3 Line=193 Msg=[The return keyword is not needed and can be removed] Src=[return inlineViolation("Number of parameters in ${name} exceeds maximum allowed (${rule.maxParameters}).")] + Violation: Rule=UnnecessaryReturnKeyword P=3 Line=253 Msg=[The return keyword is not needed and can be removed] Src=[return inlineViolation("Number of parameters in ${name} exceeds maximum allowed (${rule.maxParameters}).")] File: unnecessary/ConsecutiveStringConcatenationRuleTest.groovy Violation: Rule=GStringExpressionWithinString P=2 Line=66 Msg=[The String ' @@ -433,9 +418,6 @@ File: unnecessary/UnnecessaryPackageReferenceRuleTest.groovy ' contains a GString-type expression: '${value instanceof groovy.lang.Closure}'] Src=[final SOURCE = '''] Violation: Rule=GStringExpressionWithinString P=2 Line=75 Msg=[The String 'println "isClosure=${value instanceof groovy.lang.Closure}"' contains a GString-type expression: '${value instanceof groovy.lang.Closure}'] Src=[[lineNumber:3, sourceLineText:'println "isClosure=${value instanceof groovy.lang.Closure}"', messageText:'groovy.lang'],] -File: unnecessary/UnnecessaryPublicModifierRuleTest.groovy - Violation: Rule=MisorderedStaticImports P=3 Line=23 Msg=[Static imports should appear before normal imports] Src=[import static org.codenarc.test.TestUtil.captureLog4JMessages] - File: unused/UnusedMethodParameterRuleTest.groovy Violation: Rule=GStringExpressionWithinString P=2 Line=136 Msg=[The String ' class MyClass { @@ -456,7 +438,7 @@ File: unused/UnusedMethodParameterRuleTest.groovy ' contains a GString-type expression: '${startDate}" }'] Src=[final SOURCE = '''] File: unused/UnusedPrivateFieldRuleTest.groovy - Violation: Rule=MethodCount P=2 Line=29 Msg=[Class org.codenarc.rule.unused.UnusedPrivateFieldRuleTest has 31 methods] Src=[class UnusedPrivateFieldRuleTest extends AbstractRuleTestCase {] + Violation: Rule=MethodCount P=2 Line=29 Msg=[Class org.codenarc.rule.unused.UnusedPrivateFieldRuleTest has 32 methods] Src=[class UnusedPrivateFieldRuleTest extends AbstractRuleTestCase {] Violation: Rule=GStringExpressionWithinString P=2 Line=168 Msg=[The String ' class MyClass { private int count @@ -531,6 +513,6 @@ File: unused/UnusedPrivateMethodRuleTest.groovy ' contains a GString-type expression: '${varName}'] Src=[final SOURCE = '''] File: unused/UnusedVariableRuleTest.groovy - Violation: Rule=MethodCount P=2 Line=27 Msg=[Class org.codenarc.rule.unused.UnusedVariableRuleTest has 34 methods] Src=[class UnusedVariableRuleTest extends AbstractRuleTestCase {] + Violation: Rule=MethodCount P=2 Line=27 Msg=[Class org.codenarc.rule.unused.UnusedVariableRuleTest has 35 methods] Src=[class UnusedVariableRuleTest extends AbstractRuleTestCase {] -[CodeNarc (http://www.codenarc.org) v0.27.0] +[CodeNarc (http://www.codenarc.org) v1.0] diff --git a/src/site/resources/SampleCodeNarcXmlReport.xml b/src/site/resources/SampleCodeNarcXmlReport.xml index 72c6447c8..61f9b8db8 100644 --- a/src/site/resources/SampleCodeNarcXmlReport.xml +++ b/src/site/resources/SampleCodeNarcXmlReport.xml @@ -1,5 +1,5 @@ -src/test/groovy/org/codenarc/rulesrc/test/groovy/org/codenarc/rule \ No newline at end of file + ' contains a GString-type expression: '${varName}']]> \ No newline at end of file