CodeNarc Report

Report title:Sample Project
Date:Jan 13, 2024 11:01:23 AM
Generated with:CodeNarc v3.4.0

Summary

Total FilesFiles with ViolationsPriority 1Priority 2Priority 3
41958-7836

Violations

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

[SRC]class PrivateFieldCouldBeFinalRuleTest extends AbstractR..FinalRule> {

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

formatting/BracesForForLoopRuleTest.groovyGStringExpressionWithinString2101

[SRC]final SOURCE = '''

[MSG]The String ' for(String name=${SomeClass.SOME_CONSTANT}; name==null;) // And what about {} { doStuff() } ' contains a GString-type expression: '${SomeClass.SOME_CONSTANT}; name==null;) // And what about {}'

formatting/BracesForIfElseRuleTest.groovyGStringExpressionWithinString259

[SRC]final SOURCE = '''

[MSG]The String ' if (someContainer."${SomeClass.SOME_CONSTANT}" != null) // And what about {} { doStuff() } ' contains a GString-type expression: '${SomeClass.SOME_CONSTANT}" != null) // And what about {}'

formatting/BracesForMethodRuleTest.groovyMethodCount228

[SRC]class BracesForMethodRuleTest extends AbstractRuleTestCa..ethodRule> {

[MSG]Class org.codenarc.rule.formatting.BracesForMethodRuleTest has 38 methods

formatting/BracesForMethodRuleTest.groovyGStringExpressionWithinString2356

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { int size(String name = "${SomeClass.SOME_CONSTANT}") { return 99 } } ' contains a GString-type expression: '${SomeClass.SOME_CONSTANT}'

formatting/ClassEndsWithBlankLineRuleTest.groovyMethodCount227

[SRC]class ClassEndsWithBlankLineRuleTest extends AbstractRul..kLineRule> {

[MSG]Class org.codenarc.rule.formatting.ClassEndsWithBlankLineRuleTest has 33 methods

formatting/ClassStartsWithBlankLineRuleTest.groovyMethodCount228

[SRC]class ClassStartsWithBlankLineRuleTest extends AbstractR..kLineRule> {

[MSG]Class org.codenarc.rule.formatting.ClassStartsWithBlankLineRuleTest has 50 methods

formatting/IndentationRuleTest.groovyMethodCount226

[SRC]class IndentationRuleTest extends AbstractRuleTestCase<I..ationRule> {

[MSG]Class org.codenarc.rule.formatting.IndentationRuleTest has 58 methods

formatting/IndentationRuleTest.groovyGStringExpressionWithinString2609

[SRC]final SOURCE = '''

[MSG]The String ' |class MyClass { | private void execute() { | try { | executeWithArgs(args) | } | catch(Throwable t) { | println "ERROR: ${t.message}" | t.printStackTrace() // wrong column | } | finally { | closeResources() | } | } | private void executeOtherOne() { | try { | println 999 // wrong column | executeWithArgs(args) | } catch(Throwable t) { | t.printStackTrace() | } finally { | closeResources() | notifyUser() // wrong column | } | } |} ' contains a GString-type expression: '${t.message}'

formatting/IndentationRuleTest.groovyGStringExpressionWithinString21018

[SRC]final SOURCE = '''

[MSG]The String ' |project.files(project.configurations.scaconfig.files.findAll { File it -> it.name.endsWith '.aar' }.collect { File it -> | MessageDigest sha1 = MessageDigest.getInstance('SHA1') | String inputFile = 'COMMAND=PREPARE_LIBRARY\n' + | "FILE_PATH=${it.absolutePath}\n" | String hash = new BigInteger(1, sha1.digest(inputFile.bytes)).toString(16) | cacheDir + hash + File.separator + 'output/jars/classes.jar' |}).asFileTree ' contains a GString-type expression: '${it.absolutePath}'

formatting/IndentationRuleTest.groovyGStringExpressionWithinString21032

[SRC]final SOURCE = '''

[MSG]The String ' |"${if (true) 'content' else ''}" ' contains a GString-type expression: '${if (true) 'content' else ''}'

formatting/IndentationRuleTest.groovyGStringExpressionWithinString21040

[SRC]final SOURCE = '''

[MSG]The String ' |package com.sample | |trait RegressionTest { | | String callStackPath = "src/test/resources/callstacks/" | | /** | * Checks the current callstack is the same as the reference callstack. | * The reference callstack can be updated into a txt file in the callStackPath | * | * Pattern: <RegressionTest.callStackPath>/<ClassTestSimpleName><_subname>.txt | * @param subname optional subname, used in the reference callstack filename | */ | void testNonRegression(String subname = '') { | String targetFileName = "${callStackPath}${this.class.simpleName}" | if (subname) { | targetFileName += "_${subname}" | } | RegressionTestHelper.testNonRegression(helper, targetFileName) | } |} ' contains a GString-type expression: '${callStackPath}${this.class.simpleName}'

formatting/IndentationRule_MethodChainingTest.groovyGStringExpressionWithinString282

[SRC]final SOURCE = '''

[MSG]The String ' |buildFileList() | .collect { File it -> | MessageDigest sha1 = MessageDigest.getInstance('SHA1') | String inputFile = 'COMMAND=PREPARE_LIBRARY\n' + | "FILE_PATH=${it.absolutePath}\n" | cacheDir + File.separator + inputFile + sha1 | } | .each { name -> | println name | } |println "done" | |list2.collect { item -> | item.name |}.each { name -> println name } | |otherList.collect { item -> item.name }.each { name -> println name } | |if (expr instanceof ConstructorCallExpression || expr instanceof CastExpression) { | [Map, Iterable, List, Collection, ArrayList, Set, HashSet].findAll { | AstUtil.classNodeImplementsType(expr.type, it) | }.each { | callbackFunction() | } |} ' contains a GString-type expression: '${it.absolutePath}'

formatting/MissingBlankLineBeforeAnnotatedFieldRuleTest.groovyGStringExpressionWithinString298

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { private @Autowired DataSource dataSource private @Value('${name}') String name } ' contains a GString-type expression: '${name}'

formatting/SpaceAfterClosingBraceRuleTest.groovyGStringExpressionWithinString238

[SRC]final SOURCE = '''

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

formatting/SpaceAfterClosingBraceRuleTest.groovyGStringExpressionWithinString2304

[SRC]assertNoViolations('''

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

formatting/SpaceAfterClosingBraceRuleTest.groovyGStringExpressionWithinString2312

[SRC]assertNoViolations('''

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

formatting/SpaceAfterCommaRuleTest.groovyGStringExpressionWithinString253

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { def template() { return { td(getResourceBundleString('htmlReport.summary.allPackages'), class:'allPackages') td { a(pathName, href:"#${pathName}") } } } } ' contains a GString-type expression: '${pathName}'

formatting/SpaceAfterOpeningBraceRuleTest.groovyGStringExpressionWithinString240

[SRC]final SOURCE = '''

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

formatting/SpaceAfterOpeningBraceRuleTest.groovyGStringExpressionWithinString2102

[SRC]final SOURCE = '''

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

formatting/SpaceAfterOpeningBraceRuleTest.groovyGStringExpressionWithinString2196

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { MyClass() {int count } MyClass() {s = '{"json": true}' } MyClass(@Annotation('${prop}') String s) {println 123 } } ' contains a GString-type expression: '${prop}') String s) {println 123 }'

formatting/SpaceAfterOpeningBraceRuleTest.groovyGStringExpressionWithinString2207

[SRC][line:5, source:'MyClass(@Annotation(\'${prop}\') String..s MyClass'])

[MSG]The String 'MyClass(@Annotation('${prop}') String s) {println 123 }' contains a GString-type expression: '${prop}') String s) {println 123 }'

formatting/SpaceAfterOpeningBraceRuleTest.groovyGStringExpressionWithinString2325

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { String s MyClass() { s = '{"json": true}' } MyClass(@Annotation('${prop}') String s) { println 123 } } ' contains a GString-type expression: '${prop}') String s) { println 123 }'

formatting/SpaceBeforeClosingBraceRuleTest.groovyGStringExpressionWithinString239

[SRC]final SOURCE = '''

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

formatting/SpaceBeforeClosingBraceRuleTest.groovyGStringExpressionWithinString280

[SRC]final SOURCE = '''

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

formatting/SpaceBeforeOpeningBraceRuleTest.groovyGStringExpressionWithinString238

[SRC]final SOURCE = '''

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

formatting/SpaceBeforeOpeningBraceRuleTest.groovyGStringExpressionWithinString2277

[SRC]assertNoViolations('''

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

generic/IllegalPackageReferenceRuleTest.groovyGStringExpressionWithinString264

[SRC]final SOURCE = '''

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

generic/IllegalPackageReferenceRuleTest.groovyGStringExpressionWithinString272

[SRC][line:3, source:'println "isClosure=${value instanceof o..:'org.bad'],

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

generic/StatelessClassRuleTest.groovyGStringExpressionWithinString284

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { @Value('${org.codenarc.test}') BigDecimal depositAmount } ' contains a GString-type expression: '${org.codenarc.test}'

grails/GrailsMassAssignmentRuleTest.groovyGStringExpressionWithinString236

[SRC]final SOURCE = '''

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

grails/GrailsServletContextReferenceRuleTest.groovyGStringExpressionWithinString278

[SRC]final SOURCE = '''

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

grails/GrailsServletContextReferenceRuleTest.groovyGStringExpressionWithinString287

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

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

groovyism/ClosureAsLastMethodParameterRuleTest.groovyGStringExpressionWithinString2242

[SRC]final SOURCE = '''

[MSG]The String ' new Exception("${it.orElseThrow { new AssertionError() }}") ' contains a GString-type expression: '${it.orElseThrow { new AssertionError() }}'

groovyism/GStringAsMapKeyRuleTest.groovyGStringExpressionWithinString244

[SRC]final SOURCE = '''

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

groovyism/GStringAsMapKeyRuleTest.groovyGStringExpressionWithinString248

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

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString249

[SRC]final SOURCE = '''

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString264

[SRC]final SOURCE = '''

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString280

[SRC]final SOURCE = '''

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString293

[SRC]final SOURCE = '''

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2103

[SRC]final SOURCE = '''

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2119

[SRC]final SOURCE = '''

[MSG]The String ' def "plugin does not apply idea plugin"() { given: buildScript << """ task $testTaskName { doLast { println "Has idea plugin: \${project.plugins.hasPlugin(IdeaPlugin)}" } } """ expect: runTask(testTaskName).output.contains('Has idea plugin: false') where: testTaskName = 'hasIdeaPlugin' } ' contains a GString-type expression: '${project.plugins.hasPlugin(IdeaPlugin)}'

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2142

[SRC]final SOURCE = '''

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2147

[SRC][line:2, source:"def str1 = 'total: \${count}'", message..{count}\''],

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2147

[SRC][line:2, source:"def str1 = 'total: \${count}'", message..{count}\''],

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2148

[SRC][line:3, source:"def str2 = 'average: \${total / count}'.. count}\''])

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2148

[SRC][line:3, source:"def str2 = 'average: \${total / count}'.. count}\''])

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2153

[SRC]final SOURCE = '''

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2161

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

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2161

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

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

groovyism/GStringExpressionWithinStringRuleTest.groovyGStringExpressionWithinString2166

[SRC]final SOURCE = '''

[MSG]The String ' class SomeClass { @SomeAnnotationOnField(someClass = SomeOtherClass, message = 'Some message ${sample.property1}') String sampleProperty } ' contains a GString-type expression: '${sample.property1}'

imports/UnusedImportRuleTest.groovyGStringExpressionWithinString2215

[SRC]final SOURCE = '''

[MSG]The String ' import test.TestData1 import test.TestData2 import test.TestData3 import test.TestData4 import test.TestData5 import test.TestData6 import test.TestData7 import test.TestData8 import test.TestData9 import test.TestData10 import test.TestData11 import test.TestData12 import test.TestData13 import test.TestData14 import test.TestData15 def GSTRING1 = " ${TestData1.GOOD_XML}" def GSTRING2 = " $TestData2.XML" def MAP1 = [(TestData3):123] def MAP2 = [abc:TestData4] def MAP3 = [abc:TestData5, ddd:123] def LIST = [TestData6,TestData7] def OPERATORS1 = 0+TestData8.VALUE-TestData9.VALUE 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}'

naming/FieldNameRuleTest.groovyMethodCount228

[SRC]class FieldNameRuleTest extends AbstractRuleTestCase<FieldNameRule> {

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

unnecessary/ConsecutiveStringConcatenationRuleTest.groovyGStringExpressionWithinString265

[SRC]final SOURCE = '''

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

unnecessary/ConsecutiveStringConcatenationRuleTest.groovyGStringExpressionWithinString273

[SRC]final SOURCE = '''

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

unnecessary/UnnecessaryGStringRuleTest.groovyGStringExpressionWithinString236

[SRC]final SOURCE = '''

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

unnecessary/UnnecessaryGetterRuleTest.groovyGStringExpressionWithinString2180

[SRC]final SOURCE = '''

[MSG]The String ' Mock { getSomeData() } Stub(1,2,3) { getData2() } "${'Stub'}"(MyClass) { getData3() } def closure = { getData4() } Mock({ getData5() }, 1234) // 2nd param is not a Closure Spy { getMoreData() } ' contains a GString-type expression: '${'Stub'}'

unnecessary/UnnecessaryPackageReferenceRuleTest.groovyGStringExpressionWithinString266

[SRC]final SOURCE = '''

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

unnecessary/UnnecessaryPackageReferenceRuleTest.groovyGStringExpressionWithinString273

[SRC][line:3, source:'println "isClosure=${value instanceof g..oovy.lang'],

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

unnecessary/UnnecessarySetterRuleTest.groovyGStringExpressionWithinString297

[SRC]final SOURCE = '''

[MSG]The String ' if (!file.setExecutable(true)) { throw new Exception("Cannot set ${file} as executable") } def count = x.setCount(92) ' contains a GString-type expression: '${file}'

unnecessary/UnnecessaryToStringRuleTest.groovyGStringExpressionWithinString267

[SRC]final SOURCE = '''

[MSG]The String ' class MyClass { def name = "Joe" + new Date().toString() void run() { Object object = 1 def string = 'some string' + object.toString() def withinGString = "processing: ${'prefix' + object.toString()}" def bigString = 'some string' + new Date() + object.toString() // not a violation; known limitation def other = 123 + object.toString().toInteger() // not a violation } } ' contains a GString-type expression: '${'prefix' + object.toString()}'

unnecessary/UnnecessaryToStringRuleTest.groovyGStringExpressionWithinString284

[SRC][line:8, source:'def withinGString = "processing: ${\'pr..necessary'])

[MSG]The String 'def withinGString = "processing: ${'prefix' + object.toString()}"' contains a GString-type expression: '${'prefix' + object.toString()}'

unnecessary/UnnecessaryToStringRuleTest.groovyGStringExpressionWithinString289

[SRC]final SOURCE = '''

[MSG]The String ' def string = "some string${123L.toString()} or ${123} or ${'ABC'} or ${new Date().toString()}" def string2 = """ processing: ${123L.toString()} processing: ${new Date().toString()} """ ' contains a GString-type expression: '${123L.toString()} or ${123} or ${'ABC'} or ${new Date().toString()}'

unnecessary/UnnecessaryToStringRuleTest.groovyGStringExpressionWithinString297

[SRC][line:2, source:'def string = "some string${123L.toStrin..necessary'],

[MSG]The String 'def string = "some string${123L.toString()} or ${123} or ${'ABC'} or ${new Date().toString()}"' contains a GString-type expression: '${123L.toString()} or ${123} or ${'ABC'} or ${new Date().toString()}'

unnecessary/UnnecessaryToStringRuleTest.groovyGStringExpressionWithinString298

[SRC][line:2, source:'def string = "some string${123L.toStrin..necessary'],

[MSG]The String 'def string = "some string${123L.toString()} or ${123} or ${'ABC'} or ${new Date().toString()}"' contains a GString-type expression: '${123L.toString()} or ${123} or ${'ABC'} or ${new Date().toString()}'

unnecessary/UnnecessaryToStringRuleTest.groovyGStringExpressionWithinString299

[SRC][line:4, source:'processing: ${123L.toString()}', messag..necessary'],

[MSG]The String 'processing: ${123L.toString()}' contains a GString-type expression: '${123L.toString()}'

unnecessary/UnnecessaryToStringRuleTest.groovyGStringExpressionWithinString2100

[SRC][line:5, source:'processing: ${new Date().toString()}', ..nnecessary']

[MSG]The String 'processing: ${new Date().toString()}' contains a GString-type expression: '${new Date().toString()}'

unused/AbstractUnusedPrivateFieldRuleTest.groovyMethodCount227

[SRC]abstract class AbstractUnusedPrivateFieldRuleTest extend..FieldRule> {

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

unused/AbstractUnusedPrivateFieldRuleTest.groovyGStringExpressionWithinString2172

[SRC]final SOURCE = '''

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

unused/AbstractUnusedPrivateFieldRuleTest.groovyGStringExpressionWithinString2183

[SRC]final SOURCE = '''

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

unused/UnusedMethodParameterRuleTest.groovyGStringExpressionWithinString2150

[SRC]final SOURCE = '''

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

unused/UnusedPrivateMethodParameterRuleTest.groovyGStringExpressionWithinString2126

[SRC]final SOURCE = '''

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

unused/UnusedPrivateMethodRuleTest.groovyMethodCount226

[SRC]class UnusedPrivateMethodRuleTest extends AbstractRuleTe..ethodRule> {

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

unused/UnusedPrivateMethodRuleTest.groovyGStringExpressionWithinString2354

[SRC]final SOURCE = '''

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

unused/UnusedPrivateMethodRuleTest.groovyGStringExpressionWithinString2423

[SRC]final SOURCE = '''

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

unused/UnusedPrivateMethodRuleTest.groovyGStringExpressionWithinString2436

[SRC]final SOURCE = '''

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

unused/UnusedPrivateMethodRuleTest.groovyGStringExpressionWithinString2458

[SRC]final SOURCE = '''

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

unused/UnusedVariableRuleTest.groovyMethodCount226

[SRC]class UnusedVariableRuleTest extends AbstractRuleTestCas..iableRule> {

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

AbstractAstVisitorRuleTest.groovyUnnecessaryObjectReferences3185

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

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

AbstractAstVisitorRuleTest.groovyUnnecessaryObjectReferences3188

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

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

AbstractAstVisitorRuleTest.groovyUnnecessaryObjectReferences3189

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

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

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

comments/AbstractJavadocEmptyTagRuleTestCase.groovyUnnecessaryReturnKeyword353

[SRC]return rule.name

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

comments/AbstractJavadocEmptyTagRuleTestCase.groovyUnnecessaryReturnKeyword356

[SRC]return "The javadoc ${getTag()} tag is empty"

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

comments/AbstractJavadocMissingDescriptionRuleTestCase.groovyUnnecessaryReturnKeyword351

[SRC]return rule.name

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

comments/AbstractJavadocMissingDescriptionRuleTestCase.groovyUnnecessaryReturnKeyword354

[SRC]return "The description for the javadoc ${getTag()} tag is missing"

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

comments/JavadocEmptyAuthorTagRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@author'

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

comments/JavadocEmptyExceptionTagRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@exception'

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

comments/JavadocEmptyParamTagRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@param'

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

comments/JavadocEmptyReturnTagRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@return'

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

comments/JavadocEmptySeeTagRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@see'

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

comments/JavadocEmptySinceTagRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@since'

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

comments/JavadocEmptyThrowsTagRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@throws'

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

comments/JavadocEmptyVersionTagRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@version'

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

comments/JavadocMissingExceptionDescriptionRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@exception'

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

comments/JavadocMissingParamDescriptionRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@param'

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

comments/JavadocMissingThrowsDescriptionRuleTest.groovyUnnecessaryReturnKeyword327

[SRC]return '@throws'

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

convention/CompileStaticRuleTest.groovyUnnecessaryReturnKeyword334

[SRC]return new CompileStaticRule()

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

design/NestedForLoopRuleTest.groovyUnnecessaryReturnKeyword3106

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

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

design/OptionalCollectionReturnTypeRuleTest.groovyUnnecessaryReturnKeyword3128

[SRC]return "The method $methodName in class MyClass returns .. collection"

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

enhanced/MissingOverrideAnnotationRuleTest.groovyUnnecessaryReturnKeyword3261

[SRC]return "Method '$methodName' is overriding a method in '.. @Override."

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

formatting/BracesForTryCatchFinallyRuleTest.groovyUnnecessaryReturnKeyword3181

[SRC]return rule

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

formatting/IndentationRuleTest.groovyClassSize326

[MSG]Class "IndentationRuleTest" is 1191 lines

formatting/SpaceAroundMapEntryColonRuleTest.groovyUnnecessaryReturnKeyword3167

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

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

size/GMetricsSourceCodeAdapterTest.groovyMisorderedStaticImports322

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

[MSG]Static imports should appear before normal imports

size/ParameterCountRuleTest.groovyUnnecessaryReturnKeyword3252

[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 practice 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
60ExplicitCallToPutAtMethodDetects when the putAt(Object, Object) method is called directly in code instead of using the [] index operator. A groovier way to express this: map.putAt(k, v) is this: map[k] = v.
61ExplicitCallToRightShiftMethodThis 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
62ExplicitCallToXorMethodThis 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
63ExplicitGarbageCollectionCalls 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.
64ExplicitHashMapInstantiationThis 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.
65ExplicitHashSetInstantiationThis 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.
66ExplicitLinkedHashMapInstantiationThis 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.
67ExplicitLinkedListInstantiationThis 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.
68ExplicitStackInstantiationThis 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.
69ExplicitTreeSetInstantiationThis 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.
70ForLoopShouldBeWhileLoopA for loop without an init and update statement can be simplified to a while loop.
71GStringAsMapKeyA GString should not be used as a map key since its hashcode is not guaranteed to be stable. Consider calling key.toString().
72GStringExpressionWithinStringCheck for regular (single quote) strings containing a GString-type expression (${...}).
73GetterMethodCouldBePropertyIf 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.
74GroovyLangImmutableThe groovy.lang.Immutable annotation has been deprecated and replaced by groovy.transform.Immutable. Do not use the Immutable in groovy.lang.
75HardCodedWindowsFileSeparatorThis 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.
76HardCodedWindowsRootDirectoryThis 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.
77ImportFromSamePackageAn import of a class that is within the same package is unnecessary.
78ImportFromSunPackagesAvoid importing anything from the 'sun.*' packages. These packages are not portable and are likely to change.
79IntegerGetIntegerThis 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'].
80MethodCountA 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.
81MethodSizeChecks if the size of a method exceeds the number of lines specified by the maxLines property (100).
82MisorderedStaticImportsStatic imports should never be declared after nonstatic imports.
83MultipleUnaryOperatorsChecks for multiple consecutive unary operators. These are confusing, and are likely typos and bugs.
84NestedBlockDepthChecks for blocks or closures nested more than maxNestedBlockDepth (5) levels deep.
85NoWildcardImportsWildcard imports, static or otherwise, should not be used.
86ParameterAssignmentInFilterClosureAn assignment operator was used on a parameter in a filtering closure. This is usually a typo, and the comparison operator (==) was intended.
87ParameterCountChecks if the number of parameters in method/constructor exceeds the number of parameters specified by the maxParameters property.
88RandomDoubleCoercedToZeroThe 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.
89RemoveAllOnSelfDon'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.
90ReturnFromFinallyBlockReturning from a finally block is confusing and can hide the original exception.
91ThrowExceptionFromFinallyBlockThrowing an exception from a finally block is confusing and can hide the original exception.
92UnnecessaryBigDecimalInstantiationIt 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.
93UnnecessaryBigIntegerInstantiationIt is unnecessary to instantiate BigInteger objects. Instead just use the literal with the 'G' identifier to force the type, such as 8G or 42G.
94UnnecessaryBooleanExpressionChecks 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.
95UnnecessaryBooleanInstantiationUse 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).
96UnnecessaryCallForLastElementThis 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.
97UnnecessaryCallToSubstringCalling String.substring(0) always returns the original string. This code is meaningless.
98UnnecessaryCastChecks for unnecessary cast operations
99UnnecessaryCatchBlockViolations 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.
100UnnecessaryCollectCallSome 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.
101UnnecessaryCollectionCallUseless 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.
102UnnecessaryConstructorThis 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.
103UnnecessaryDefInFieldDeclarationIf 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 = {}.
104UnnecessaryDefInMethodDeclarationIf 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() {}'.
105UnnecessaryDefInVariableDeclarationIf 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'.
106UnnecessaryDotClassTo make a reference to a class, it is unnecessary to specify the '.class' identifier. For instance String.class can be shortened to String.
107UnnecessaryDoubleInstantiationIt 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.
108UnnecessaryElseStatementWhen 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.
109UnnecessaryFinalOnPrivateMethodA private method is marked final. Private methods cannot be overridden, so marking it final is unnecessary.
110UnnecessaryFloatInstantiationIt 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.
111UnnecessaryGStringString 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.
112UnnecessaryGroovyImportA 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.
113UnnecessaryIfStatementChecks 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.
114UnnecessaryInstanceOfCheckThis 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.
115UnnecessaryInstantiationToGetClassAvoid instantiating an object just to call getClass() on it; use the .class public member instead.
116UnnecessaryIntegerInstantiationIt is unnecessary to instantiate Integer objects. Instead just use the literal with the 'I' identifier to force the type, such as 8I or 42i.
117UnnecessaryLongInstantiationIt is unnecessary to instantiate Long objects. Instead just use the literal with the 'L' identifier to force the type, such as 8L or 42L.
118UnnecessaryModOneAny 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).
119UnnecessaryNullCheckGroovy contains the safe dereference operator, which can be used in boolean conditional statements to safely replace explicit "x == null" tests.
120UnnecessaryNullCheckBeforeInstanceOfThere is no need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.
121UnnecessaryObjectReferencesViolations 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.
122UnnecessaryOverridingMethodThe overriding method merely calls the same method defined in a superclass
123UnnecessaryPackageReferenceChecks for explicit package reference for classes that Groovy imports by default, such as java.lang.String, java.util.Map and groovy.lang.Closure.
124UnnecessaryParenthesesForMethodCallWithClosureIf 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.
125UnnecessaryPublicModifierThe 'public' modifier is not required on methods or classes.
126UnnecessaryReturnKeywordIn 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.
127UnnecessarySafeNavigationOperatorCheck for the safe navigation operator (?.) applied to constants and literals, which can never be null.
128UnnecessarySelfAssignmentMethod contains a pointless self-assignment to a variable or property.
129UnnecessarySemicolonSemicolons 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.
130UnnecessarySetterChecks 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.
131UnnecessaryStringInstantiationUse a String literal (e.g., "...") instead of calling the corresponding String constructor (new String("..")) directly.
132UnnecessaryTernaryExpressionChecks 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.
133UnnecessaryToStringChecks for unnecessary calls to toString().
134UnnecessaryTransientModifierThe field is marked as transient, but the class isn't Serializable, so marking it as transient has no effect.
135UnusedImportImports for a class that is never referenced within the source file is unnecessary.
136UseCollectManyIn many case collectMany() yields the same result as collect{}.flatten(). It is easier to understand and more clearly conveys the intent.
137UseCollectNestedInstead of nested collect{}-calls use collectNested{}