CodeNarc Report

Report title:
Date:Apr 11, 2017 2:27:14 PM
Generated with:CodeNarc v0.25.1

Summary

PackageTotal FilesFiles with ViolationsPriority 1Priority 2Priority 3
All Packages4720-1930
com/stehno/vanilla1----
com/stehno/vanilla/config31--1
com/stehno/vanilla/io85-71
com/stehno/vanilla/jdbc21-1-
com/stehno/vanilla/jdbc/mapper/runtime22-19
com/stehno/vanilla/jdbc/mapper/transform11-2-
com/stehno/vanilla/mapper31--1
com/stehno/vanilla/mapper/transform1----
com/stehno/vanilla/matcher1----
com/stehno/vanilla/overlap31--2
com/stehno/vanilla/test115-78
com/stehno/vanilla/test/jdbc/mock2----
com/stehno/vanilla/text32-17
com/stehno/vanilla/transform31--1
com/stehno/vanilla/util3----

Package: com.stehno.vanilla.config

➥ CompositeConfigurationSourceSpec.groovy

Rule NamePriorityLine #Source Line / Message
SpaceBeforeOpeningBrace347

[SRC]def 'inject new source'(){

[MSG]The opening brace for the method in class com.stehno.vanilla.config.CompositeConfigurationSourceSpec is not preceded by a space or whitespace

Package: com.stehno.vanilla.io

➥ DefaultRolloverFileProviderSpec.groovy

Rule NamePriorityLine #Source Line / Message
NonFinalPublicField224

[SRC]@Rule public TemporaryFolder folder = new TemporaryFolder()

[MSG]Violation in class com.stehno.vanilla.io.DefaultRolloverFileProviderSpec. The field folder is public but not final, which violates secure coding principles

➥ DirectoryDifferenceCollectorTest.groovy

Rule NamePriorityLine #Source Line / Message
FactoryMethodName260

[SRC]private static File createFile(File folder, String name,..g content) {

[MSG]Violation in class DirectoryDifferenceCollectorTest. The method 'createFile' matches the regular expression /(build.*|create.*)/ and does not appear in a class matching /*.Builder/

➥ FileSizeRolloverTriggerStrategySpec.groovy

Rule NamePriorityLine #Source Line / Message
NonFinalPublicField229

[SRC]@Rule public TemporaryFolder folder = new TemporaryFolder()

[MSG]Violation in class com.stehno.vanilla.io.FileSizeRolloverTriggerStrategySpec. The field folder is public but not final, which violates secure coding principles

PrivateFieldCouldBeFinal331

[SRC]private FileSizeRolloverTriggerStrategy strategy = new F..y(10, BYTES)

[MSG]Private field [strategy] in class com.stehno.vanilla.io.FileSizeRolloverTriggerStrategySpec is only set within the field initializer or a constructor, and so it can be made final.

➥ RollingFileSpec.groovy

Rule NamePriorityLine #Source Line / Message
NonFinalPublicField224

[SRC]@Rule public TemporaryFolder folder = new TemporaryFolder()

[MSG]Violation in class com.stehno.vanilla.io.RollingFileSpec. The field folder is public but not final, which violates secure coding principles

➥ StorageUnitSpec.groovy

Rule NamePriorityLine #Source Line / Message
CyclomaticComplexity223

[SRC]class StorageUnitSpec extends Specification {

[MSG]The average method cyclomatic complexity for class [com.stehno.vanilla.io.StorageUnitSpec] is [27.0]

CyclomaticComplexity225

[SRC]@Unroll

[MSG]Violation in class com.stehno.vanilla.io.StorageUnitSpec. The cyclomatic complexity for method [convert: #source to #desired] is [27]

CyclomaticComplexity263

[SRC]@Unroll

[MSG]Violation in class com.stehno.vanilla.io.StorageUnitSpec. The cyclomatic complexity for method [approximate: #source to #desired] is [27]

Package: com.stehno.vanilla.jdbc

➥ DummyObjectC.groovy

Rule NamePriorityLine #Source Line / Message
FieldName229

[SRC]private byte _somethingElse

[MSG]The fieldname _somethingElse in class com.stehno.vanilla.jdbc.DummyObjectC does not match [a-z][a-zA-Z0-9]*

Package: com.stehno.vanilla.jdbc.mapper.runtime

➥ RuntimeFieldMappingSpec.groovy

Rule NamePriorityLine #Source Line / Message
JdbcResultSetReference220

[SRC]import java.sql.ResultSet

[MSG]Found reference to java.sql.ResultSet

MissingBlankLineAfterPackage316

[SRC]import com.stehno.vanilla.jdbc.mapper.FieldMapping

[MSG]Missing blank line after package statement in file RuntimeFieldMappingSpec.groovy

SpaceBeforeOpeningBrace326

[SRC]private final ResultSet resultSet = GroovyMock(ResultSet){

[MSG]The opening brace for the closure in class com.stehno.vanilla.jdbc.mapper.runtime.RuntimeFieldMappingSpec is not preceded by a space or whitespace

SpaceBeforeOpeningBrace331

[SRC]def 'extract: number'(){

[MSG]The opening brace for the method in class com.stehno.vanilla.jdbc.mapper.runtime.RuntimeFieldMappingSpec is not preceded by a space or whitespace

SpaceAfterComma337

[SRC]fieldMapping.extractor.call(resultSet,'') == TEST_LONG

[MSG]The parameter in the call to method call within class com.stehno.vanilla.jdbc.mapper.runtime.RuntimeFieldMappingSpec is not preceded by a space or whitespace

SpaceBeforeOpeningBrace340

[SRC]def 'extract: string'(){

[MSG]The opening brace for the method in class com.stehno.vanilla.jdbc.mapper.runtime.RuntimeFieldMappingSpec is not preceded by a space or whitespace

SpaceAfterComma346

[SRC]fieldMapping.extractor.call(resultSet,'') == TEST_LONG

[MSG]The parameter in the call to method call within class com.stehno.vanilla.jdbc.mapper.runtime.RuntimeFieldMappingSpec is not preceded by a space or whitespace

SpaceBeforeOpeningBrace349

[SRC]def 'extract: gstring'(){

[MSG]The opening brace for the method in class com.stehno.vanilla.jdbc.mapper.runtime.RuntimeFieldMappingSpec is not preceded by a space or whitespace

SpaceAfterComma358

[SRC]fieldMapping.extractor.call(resultSet,'') == TEST_LONG

[MSG]The parameter in the call to method call within class com.stehno.vanilla.jdbc.mapper.runtime.RuntimeFieldMappingSpec is not preceded by a space or whitespace

➥ RuntimeResultSetMapperSpec.groovy

Rule NamePriorityLine #Source Line / Message
SpaceBeforeOpeningBrace3111

[SRC]def mapper = mapper(DummyObjectA, EXPLICIT){

[MSG]The opening brace for the closure in class com.stehno.vanilla.jdbc.mapper.runtime.RuntimeResultSetMapperSpec is not preceded by a space or whitespace

Package: com.stehno.vanilla.jdbc.mapper.transform

➥ InjectResultSetMapperTransformSpec.groovy

Rule NamePriorityLine #Source Line / Message
GStringExpressionWithinString2298

[SRC]def mapper = shell.evaluate('''

[MSG]The String ' package testing import com.stehno.vanilla.jdbc.mapper.MappingStyle import com.stehno.vanilla.jdbc.mapper.ResultSetMapper import com.stehno.vanilla.jdbc.mapper.annotation.InjectResultSetMapper import static com.stehno.vanilla.jdbc.mapper.MappingStyle.EXPLICIT class Foo { String name int number @InjectResultSetMapper(value=Foo, style=EXPLICIT, config={ map 'name' from 'first_name' using { fn, rs-> "$fn ${rs.getString('last_name')}"} map 'number' }) static ResultSetMapper mapper(){} } Foo.mapper() ' contains a GString-type expression: '${rs.getString('last_name')}"}'

GStringExpressionWithinString2338

[SRC]def mapper = shell.evaluate('''

[MSG]The String ' package testing import com.stehno.vanilla.jdbc.mapper.MappingStyle import com.stehno.vanilla.jdbc.mapper.ResultSetMapper import com.stehno.vanilla.jdbc.mapper.annotation.InjectResultSetMapper import static com.stehno.vanilla.jdbc.mapper.MappingStyle.EXPLICIT class Foo { String name int number @InjectResultSetMapper(value=Foo, style=EXPLICIT, config={ map 'name' from 'first_name' using { fn, rs-> "$fn ${rs.getString('last_name')}"} map 'number' }) static ResultSetMapper mapper(){} } Foo.mapper() ' contains a GString-type expression: '${rs.getString('last_name')}"}'

Package: com.stehno.vanilla.mapper

➥ ObjectMapperSpec.groovy

Rule NamePriorityLine #Source Line / Message
ConsecutiveBlankLines3302

[MSG]File ObjectMapperSpec.groovy has consecutive blank lines

Package: com.stehno.vanilla.overlap

➥ OverlappableSpec.groovy

Rule NamePriorityLine #Source Line / Message
SpaceBeforeOpeningBrace324

[SRC]def 'overlaps: positive'(){

[MSG]The opening brace for the method in class com.stehno.vanilla.overlap.OverlappableTraitSpec is not preceded by a space or whitespace

SpaceBeforeOpeningBrace333

[SRC]def 'overlaps: negative'(){

[MSG]The opening brace for the method in class com.stehno.vanilla.overlap.OverlappableTraitSpec is not preceded by a space or whitespace

Package: com.stehno.vanilla.test

➥ AssertionsSpec.groovy

Rule NamePriorityLine #Source Line / Message
FieldName228

[SRC]private static final Fixture fixture = FixtureBuilder.define {

[MSG]The fieldname fixture in class com.stehno.vanilla.test.AssertionsSpec does not match [A-Z][A-Z0-9_]*

➥ FixtureBuilderSpec.groovy

Rule NamePriorityLine #Source Line / Message
SpaceAfterOpeningBrace369

[SRC]define {}.map('blah')

[MSG]The opening brace for the closure in class com.stehno.vanilla.test.FixtureBuilderSpec is not followed by a space or whitespace

SpaceBeforeClosingBrace369

[SRC]define {}.map('blah')

[MSG]The closing brace for the closure in class com.stehno.vanilla.test.FixtureBuilderSpec is not preceded by a space or whitespace

SpaceAfterOpeningBrace377

[SRC]define {}.map()

[MSG]The opening brace for the closure in class com.stehno.vanilla.test.FixtureBuilderSpec is not followed by a space or whitespace

SpaceBeforeClosingBrace377

[SRC]define {}.map()

[MSG]The closing brace for the closure in class com.stehno.vanilla.test.FixtureBuilderSpec is not preceded by a space or whitespace

➥ MicroBenchSpec.groovy

Rule NamePriorityLine #Source Line / Message
ConfusingMethodName224

[SRC]def 'bench'() {

[MSG]The method name bench is similar to the field name bench

ExplicitHashSetInstantiation239

[SRC]Set<String> data = new HashSet<String>()

[MSG]HashSet objects are better instantiated using the form "[] as Set"

SpaceAroundClosureArrow333

[SRC]count.times { n->

[MSG]The closure arrow (->) within class com.stehno.vanilla.test.MicroBenchSpec is not surrounded by a space or whitespace

SpaceAfterFor340

[SRC]for( final String s : items ){

[MSG]The for keyword within class com.stehno.vanilla.test.MicroBenchSpec is not followed by a single space

SpaceBeforeOpeningBrace340

[SRC]for( final String s : items ){

[MSG]The opening brace for the block in class com.stehno.vanilla.test.MicroBenchSpec is not preceded by a space or whitespace

➥ PropertyRandomizerTest.groovy

Rule NamePriorityLine #Source Line / Message
ConsecutiveBlankLines3226

[MSG]File PropertyRandomizerTest.groovy has consecutive blank lines

➥ RandomizersSpec.groovy

Rule NamePriorityLine #Source Line / Message
InsecureRandom232

[SRC]private final Random random = new Random()

[MSG]Using Random is insecure. Use SecureRandom instead

ConfusingMethodName238

[SRC]def 'random'() {

[MSG]The method name random is similar to the field name random

LongLiteralWithLowerCaseL2138

[SRC]'Long' | 10l..100l

[MSG]The literal 100l should be rewritten 100L

GStringExpressionWithinString2253

[SRC]'($area) ${prefix}-${number}',

[MSG]The String '($area) ${prefix}-${number}' contains a GString-type expression: '${prefix}-${number}'

Package: com.stehno.vanilla.text

➥ TextFileReaderSpec.groovy

Rule NamePriorityLine #Source Line / Message
UnnecessarySemicolon316

[SRC]package com.stehno.vanilla.text;

[MSG]Semi-colons as line endings can be removed safely

UnnecessarySemicolon322

[SRC]import java.nio.file.Paths;

[MSG]Semi-colons as line endings can be removed safely

➥ TextFileWriterSpec.groovy

Rule NamePriorityLine #Source Line / Message
NonFinalPublicField224

[SRC]@Rule public TemporaryFolder folder = new TemporaryFolder()

[MSG]Violation in class com.stehno.vanilla.text.TextFileWriterSpec. The field folder is public but not final, which violates secure coding principles

SpaceBeforeOpeningBrace326

[SRC]def 'writer'(){

[MSG]The opening brace for the method in class com.stehno.vanilla.text.TextFileWriterSpec is not preceded by a space or whitespace

SpaceAfterComma337

[SRC]writer.write(['a','b','c'])

[MSG]The list element b within class com.stehno.vanilla.text.TextFileWriterSpec is not preceded by a space or whitespace

SpaceAfterComma337

[SRC]writer.write(['a','b','c'])

[MSG]The list element c within class com.stehno.vanilla.text.TextFileWriterSpec is not preceded by a space or whitespace

SpaceAfterComma338

[SRC]writer.write(['d','e','f'] as Object[])

[MSG]The list element e within class com.stehno.vanilla.text.TextFileWriterSpec is not preceded by a space or whitespace

SpaceAfterComma338

[SRC]writer.write(['d','e','f'] as Object[])

[MSG]The list element f within class com.stehno.vanilla.text.TextFileWriterSpec is not preceded by a space or whitespace

Package: com.stehno.vanilla.transform

➥ LazyImmutableTransformSpec.groovy

Rule NamePriorityLine #Source Line / Message
MissingBlankLineAfterImports3198

[SRC]@LazyImmutable @EqualsAndHashCode

[MSG]Missing blank line after imports in file LazyImmutableTransformSpec.groovy

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.
2AbstractClassNameVerifies that the name of an abstract class matches a regular expression specified in the regex property. If that property is null or empty, then this rule is not applied (i.e., it does nothing). It defaults to null, so this rule must be explicitly configured to be active. This rule ignores interfaces.
3AbstractClassWithPublicConstructorChecks for abstract classes that define a public constructor, which is useless and confusing.
4AbstractClassWithoutAbstractMethodThe abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods. If the class is intended to be used as a base class only (not to be instantiated direcly) a protected constructor can be provided prevent direct instantiation.
5AddEmptyStringFinds empty string literals which are being added. This is an inefficient way to convert any type to a String.
6AssertWithinFinallyBlockChecks for assert statements within a finally block. An assert can throw an exception, hiding the original exception, if there is one.
7AssignCollectionSortThe 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.
8AssignCollectionUniqueThe 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.
9AssignmentInConditionalAn assignment operator (=) was used in a conditional test. This is usually a typo, and the comparison operator (==) was intended.
10BigDecimalInstantiationChecks for calls to the BigDecimal constructors that take a double parameter, which may result in an unexpected BigDecimal value.
11BitwiseOperatorInConditionalChecks for bitwise operations in conditionals, if you need to do a bitwise operation then it is best practive to extract a temp variable.
12BooleanGetBooleanThis 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'].
13BooleanMethodReturnsNullMethod with Boolean return type returns explicit null. A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen. This method can be invoked as though it returned a value of type boolean, and the compiler will insert automatic unboxing of the Boolean value. If a null value is returned, this will result in a NullPointerException.
14BracesForClassChecks the location of the opening brace ({) for classes. By default, requires them on the same line, but the sameLine property can be set to false to override this.
15BracesForForLoopChecks the location of the opening brace ({) for for loops. By default, requires them on the same line, but the sameLine property can be set to false to override this.
16BracesForIfElseChecks the location of the opening brace ({) for if statements. By default, requires them on the same line, but the sameLine property can be set to false to override this.
17BracesForMethodChecks the location of the opening brace ({) for constructors and methods. By default, requires them on the same line, but the sameLine property can be set to false to override this.
18BracesForTryCatchFinallyChecks the location of the opening brace ({) for try statements. By default, requires them on the line, but the sameLine property can be set to false to override this.
19BrokenNullCheckLooks for faulty checks for null that can cause a NullPointerException.
20BrokenOddnessCheckThe 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.
21BuilderMethodWithSideEffectsA builder method is defined as one that creates objects. As such, they should never be of void return type. If a method is named build, create, or make, then it should always return a value.
22BusyWaitBusy waiting (forcing a Thread.sleep() while waiting on a condition) should be avoided. Prefer using the gate and barrier objects in the java.util.concurrent package.
23CatchArrayIndexOutOfBoundsExceptionCheck the size of the array before accessing an array element rather than catching ArrayIndexOutOfBoundsException.
24CatchErrorCatching Error is dangerous; it can catch exceptions such as ThreadDeath and OutOfMemoryError.
25CatchExceptionCatching Exception is often too broad or general. It should usually be restricted to framework or infrastructure code, rather than application code.
26CatchIllegalMonitorStateExceptionDubious catching of IllegalMonitorStateException. IllegalMonitorStateException is generally only thrown in case of a design flaw in your code (calling wait or notify on an object you do not hold a lock on).
27CatchIndexOutOfBoundsExceptionCheck that an index is valid before accessing an indexed element rather than catching IndexOutOfBoundsException.
28CatchNullPointerExceptionCatching NullPointerException is never appropriate. It should be avoided in the first place with proper null checking, and it can mask underlying errors.
29CatchRuntimeExceptionCatching RuntimeException is often too broad or general. It should usually be restricted to framework or infrastructure code, rather than application code.
30CatchThrowableCatching Throwable is dangerous; it can catch exceptions such as ThreadDeath and OutOfMemoryError.
31ChainedTestA test method that invokes another test method is a chained test; the methods are dependent on one another. Tests should be isolated, and not be dependent on one another.
32ClassForNameUsing 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.
33ClassNameVerifies that the name of a class matches a regular expression. By default it checks that the class name starts with an uppercase letter and is followed by zero or more word characters (letters, numbers or underscores). The regex property specifies the regular expression used to validate the class name.
34ClassNameSameAsFilenameReports files containing only one top level class / enum / interface which is named differently than the file.
35ClassSizeChecks if the size of a class exceeds the number of lines specified by the maxLines property (1000).
36CloneWithoutCloneableThe method clone() should only be declared if the class implements the Cloneable interface.
37CloneableWithoutCloneA class that implements java.lang.Cloneable should define a clone() method.
38CloseWithoutCloseableIf a class defines a "void close()" then that class should implement java.io.Closeable.
39ClosureAsLastMethodParameterIf a method is called and the last parameter is an inline closure then it can be declared outside of the method call brackets.
40ClosureStatementOnOpeningLineOfMultipleLineClosureChecks for closure logic on first line (after ->) for a multi-line closure.
41CollectAllIsDeprecatedcollectAll{} is deprecated since Groovy 1.8.1. Use collectNested instead{}.
42CompareToWithoutComparableIf you implement a compareTo method then you should also implement the Comparable interface. If you don't then you could possibly get an exception if the Groovy == operator is invoked on your object. This is an issue fixed in Groovy 1.8 but present in previous versions.
43ComparisonOfTwoConstantsChecks 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].
44ComparisonWithSelfChecks 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.
45ConfusingClassNamedExceptionThis class is not derived from another exception, but ends with 'Exception'. This will be confusing to users of this class.
46ConfusingMethodNameChecks for confusing method names. The referenced methods have names that differ only by capitalization. This is very confusing because if the capitalization were identical then one of the methods would override the other.
47ConfusingMultipleReturnsMultiple 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.
48ConfusingTernaryIn a ternary expression avoid negation in the test. For example, rephrase: "(x != y) ? diff : same" as: "(x == y) ? same : diff". Consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as "does the error case go first?" or "does the common case go first?".
49ConsecutiveBlankLinesMakes sure there are no consecutive lines that are either blank or whitespace only.
50ConsecutiveLiteralAppendsViolations occur when method calls to append(Object) are chained together with literals as parameters. The chained calls can be joined into one invocation.
51ConsecutiveStringConcatenationCatches concatenation of two string literals on the same line. These can safely by joined.
52ConstantAssertExpressionChecks for assert statements where the assert boolean condition expression is a constant or literal value.
53ConstantIfExpressionChecks for if statements with a constant value for the if expression, such as true, false, null, or a literal constant value.
54ConstantTernaryExpressionChecks for ternary expressions with a constant value for the boolean expression, such as true, false, null, or a literal constant value.
55ConstantsOnlyInterfaceAn interface should be used only to model a behaviour of a class: using an interface as a container of constants is a poor usage pattern.
56CouldBeElvisCatch an if block that could be written as an elvis expression.
57CoupledTestCaseThis rule finds test cases that are coupled to other test cases, either by invoking static methods on another test case or by creating instances of another test case. If you require shared logic in test cases then extract that logic to a new class where it can properly be reused.
58CyclomaticComplexityChecks 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.
59DeadCodeDead 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.
60DirectConnectionManagementThe J2EE standard requires that applications use the container's resource management facilities to obtain connections to resources. Every major web application container provides pooled database connection management as part of its resource management framework. Duplicating this functionality in an application is difficult and error prone, which is part of the reason it is forbidden under the J2EE standard.
61DoubleCheckedLockingThis rule detects double checked locking, where a 'lock hint' is tested for null before initializing an object within a synchronized block. Double checked locking does not guarantee correctness and is an anti-pattern.
62DoubleNegativeThere 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.
63DuplicateCaseStatementCheck for duplicate case statements in a switch block, such as two equal integers or strings.
64DuplicateImportDuplicate import statements are unnecessary.
65DuplicateMapKeyA map literal is created with duplicated key. The map entry will be overwritten.
66DuplicateSetValueA Set literal is created with duplicate constant value. A set cannot contain two elements with the same value.
67ElseBlockBracesUse braces for else blocks, even for a single statement. By default, braces are not required for an else if it is followed immediately by an if. Set the bracesRequiredForElseIf property to true to require braces is that situation as well.
68EmptyCatchBlockIn most cases, exceptions should not be caught and ignored (swallowed).
69EmptyClassReports classes without methods, fields or properties. Why would you need a class like this?
70EmptyElseBlockEmpty else blocks are confusing and serve no purpose.
71EmptyFinallyBlockEmpty finally blocks are confusing and serve no purpose.
72EmptyForStatementEmpty for statements are confusing and serve no purpose.
73EmptyIfStatementEmpty if statements are confusing and serve no purpose.
74EmptyInstanceInitializerAn empty class instance initializer was found. It is safe to remove it.
75EmptyMethodA method was found without an implementation. If the method is overriding or implementing a parent method, then mark it with the @Override annotation.
76EmptyMethodInAbstractClassAn empty method in an abstract class should be abstract instead, as developer may rely on this empty implementation rather than code the appropriate one.
77EmptyStaticInitializerAn empty static initializer was found. It is safe to remove it.
78EmptySwitchStatementEmpty switch statements are confusing and serve no purpose.
79EmptySynchronizedStatementEmpty synchronized statements are confusing and serve no purpose.
80EmptyTryBlockEmpty try blocks are confusing and serve no purpose.
81EmptyWhileStatementEmpty while statements are confusing and serve no purpose.
82EnumCustomSerializationIgnoredChecks for enums that define writeObject() or writeReplace() methods, or declare serialPersistentFields or serialVersionUID fields, all of which are ignored for enums.
83EqualsAndHashCodeIf either the boolean equals(Object) or the int hashCode() methods are overridden within a class, then both must be overridden.
84EqualsOverloadedThe 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.
85ExceptionExtendsErrorErrors are system exceptions. Do not extend them.
86ExceptionExtendsThrowableChecks for classes that extend java.lang.Throwable. Custom exception classes should subclass java.lang.Exception or one of its descendants.
87ExceptionNotThrownChecks for an exception constructor call without a throw as the last statement within a catch block.
88ExplicitArrayListInstantiationThis 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.
89ExplicitCallToAndMethodThis 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
90ExplicitCallToCompareToMethodThis 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.
91ExplicitCallToDivMethodThis 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
92ExplicitCallToEqualsMethodThis 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
93ExplicitCallToGetAtMethodThis 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]
94ExplicitCallToLeftShiftMethodThis 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
95ExplicitCallToMinusMethodThis 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
96ExplicitCallToModMethodThis 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
97ExplicitCallToMultiplyMethodThis 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
98ExplicitCallToOrMethodThis 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
99ExplicitCallToPlusMethodThis 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
100ExplicitCallToPowerMethodThis 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
101ExplicitCallToRightShiftMethodThis 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
102ExplicitCallToXorMethodThis 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
103ExplicitGarbageCollectionCalls 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.
104ExplicitHashMapInstantiationThis 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.
105ExplicitHashSetInstantiationThis 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.
106ExplicitLinkedHashMapInstantiationThis 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.
107ExplicitLinkedListInstantiationThis 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.
108ExplicitStackInstantiationThis 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.
109ExplicitTreeSetInstantiationThis 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.
110FactoryMethodNameA factory method is a method that creates objects, and they are typically named either buildFoo(), makeFoo(), or createFoo(). This rule enforces that only one naming convention is used. It defaults to makeFoo(), but that can be changed using the property 'regex'.
111FieldNameVerifies that the name of each field matches a regular expression. By default it checks that non-'final' field names start with a lowercase letter and contains only letters or numbers, and 'final' field names start with an uppercase letter and contain only uppercase letters, numbers and underscores. The regex property specifies the default regular expression used to validate field names. The finalRegex property specifies the regular expression to validate 'final' field names. The staticRegex property specifies the regular expression to validate 'static' field names. The staticFinalRegex property specifies the regular expression to validate 'static final' field names. The ignoreFieldNames property (serialVersionUID)can specify field names that should be ignored, optionally containing wildcard characters ('*' or '?').
112FileCreateTempFileThe File.createTempFile() method is insecure, and has been deprecated by the ESAPI secure coding library. It has been replaced by the ESAPI Randomizer.getRandomFilename(String) method.
113FinalClassWithProtectedMemberThis rule finds classes marked final that contain protected methods. If a class is final then it may not be subclassed, and there is therefore no point in having a method with protected visibility. Either the class should not be final or the method should be private or protected.
114ForLoopShouldBeWhileLoopA for loop without an init and update statement can be simplified to a while loop.
115ForStatementBracesUse braces for for statements, even for a single statement.
116GStringAsMapKeyA GString should not be used as a map key since its hashcode is not guaranteed to be stable. Consider calling key.toString().
117GStringExpressionWithinStringCheck for regular (single quote) strings containing a GString-type expression (${...}).
118GetterMethodCouldBePropertyIf 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.
119GrailsDomainHasEqualsChecks that Grails domain classes redefine equals().
120GrailsDomainHasToStringChecks that Grails domain classes redefine toString()
121GrailsDomainReservedSqlKeywordNameForbids usage of SQL reserved keywords as class or field names in Grails domain classes. Naming a domain class (or its field) with such a keyword causes SQL schema creation errors and/or redundant table/column name mappings.
122GrailsDomainWithServiceReferenceChecks that Grails domain classes do not have service classes injected.
123GrailsDuplicateConstraintCheck for duplicate entry in domain class constraints
124GrailsDuplicateMappingCheck for duplicate name in a domain class mapping
125GrailsMassAssignmentUntrusted input should not be allowed to set arbitrary object fields without restriction.
126GrailsServletContextReferenceChecks for references to the servletContext object from within Grails controller and taglib classes.
127GrailsStatelessServiceChecks for fields on Grails service classes. Grails service classes are singletons, by default, and so they should be reentrant and typically stateless. The ignoreFieldNames property (dataSource,scope,sessionFactory,transactional,*Service) specifies one or more field names that should be ignored. The ignoreFieldTypes property (null) specifies one or more field type names that should be ignored. Both can optionally contain wildcard characters ('*' or '?').
128GroovyLangImmutableThe groovy.lang.Immutable annotation has been deprecated and replaced by groovy.transform.Immutable. Do not use the Immutable in groovy.lang.
129HardCodedWindowsFileSeparatorThis 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.
130HardCodedWindowsRootDirectoryThis 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.
131HashtableIsObsoleteThe java.util.Hashtable class is effectively obsolete. Use the Java Collections Framework classes instead, including HashMap or ConcurrentHashMap. See the JDK javadoc.
132IfStatementBracesUse braces for if statements, even for a single statement.
133IfStatementCouldBeTernaryChecks for if statements where both the if and else blocks contain only a single return statement with a constant or literal value
134IllegalClassMemberChecks for classes containing fields/properties/methods matching configured illegal member modifiers or not matching any of the configured allowed member modifiers.
135IllegalClassReferenceChecks for reference to any of the classes configured in classNames.
136IllegalPackageReferenceChecks for reference to any of the packages configured in packageNames.
137IllegalRegexChecks for a specified illegal regular expression within the source code. The regex property specifies the regular expression to check for. It is required and cannot be null or empty.
138IllegalStringChecks for a specified illegal string within the source code.
139IllegalSubclassChecks for classes that extend one of the specified set of illegal superclasses configured in superclassNames.
140ImplementationAsTypeChecks for use of a predefined set of concrete classes (e.g. ArrayList, Hashtable, ConcurrentHashMap) when specifying the type of a method parameter, closure parameter, constructor parameter, method return type or field type. The associated interfaces should be used to specify the type instead.
141ImportFromSamePackageAn import of a class that is within the same package is unnecessary.
142ImportFromSunPackagesAvoid importing anything from the 'sun.*' packages. These packages are not portable and are likely to change.
143InconsistentPropertyLockingClass contains similarly-named get and set methods where one method of the pair is marked either @WithReadLock or @WithWriteLock and the other is not locked at all.
144InconsistentPropertySynchronizationClass contains similarly-named get and set methods where the set method is synchronized and the get method is not, or the get method is synchronized and the set method is not.
145InsecureRandomReports usages of java.util.Random, which can produce very predictable results. If two instances of Random are created with the same seed and sequence of method calls, they will generate the exact same results. Use java.security.SecureRandom instead, which provides a cryptographically strong random number generator. SecureRandom uses PRNG, which means they are using a deterministic algorithm to produce a pseudo-random number from a true random seed. SecureRandom produces non-deterministic output.
146IntegerGetIntegerThis 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'].
147InterfaceNameVerifies that the name of an interface matches a regular expression specified in the regex property. If that property is null or empty, then this rule is not applied (i.e., it does nothing). It defaults to null, so this rule must be explicitly configured to be active.
148InvertedIfElseAn inverted if-else statement is one in which there is a single if statement with a single else branch and the boolean test of the if is negated. For instance if (!x) false else true. It is usually clearer to write this as if (x) true else false.
149JUnitAssertAlwaysFailsChecks for JUnit assert() method calls with constant arguments such that the assertion always fails. This includes: assertTrue(false), assertFalse(true) and assertNull(CONSTANT).
150JUnitAssertAlwaysSucceedsChecks for JUnit assert() method calls with constant arguments such that the assertion always succeeds. This includes: assertTrue(true), assertFalse(false) and assertNull(null).
151JUnitAssertEqualsConstantActualValueReports usages of org.junit.Assert.assertEquals([message,] expected, actual) where the 'actual' parameter is a constant or a literal. Most likely it was intended to be the 'expected' value.
152JUnitFailWithoutMessageThis rule detects JUnit calling the fail() method without an argument. For better error reporting you should always provide a message.
153JUnitLostTestChecks for classes that import JUnit 4 classes and contain a public, instance, void, no-arg method named test* that is not annotated with @Test.
154JUnitPublicFieldChecks for public field on a JUnit test class
155JUnitPublicNonTestMethodChecks if a JUnit test class contains public methods other than standard test methods, JUnit framework methods or methods with JUnit annotations.
156JUnitPublicPropertyChecks for public properties defined on JUnit test classes. There should be no need to expose a public property on a test class.
157JUnitSetUpCallsSuperChecks that if the JUnit setUp() method is defined, that it includes a call to super.setUp().
158JUnitStyleAssertionsThis rule detects calling JUnit style assertions like assertEquals, assertTrue, assertFalse, assertNull, assertNotNull. Groovy 1.7 ships with a feature called the "power assert", which is an assert statement with better error reporting. This is preferable to the JUnit assertions.
159JUnitTearDownCallsSuperChecks that if the JUnit tearDown() method is defined, that it includes a call to super.tearDown().
160JUnitTestMethodWithoutAssertThis rule searches for test methods that do not contain assert statements. Either the test method is missing assert statements, which is an error, or the test method contains custom assert statements that do not follow a proper assert naming convention. Test methods are defined as public void methods that begin with the work test or have a @Test annotation. By default this rule applies to the default test class names, but this can be changed using the rule's applyToClassNames property.
161JUnitUnnecessarySetUpChecks for JUnit setUp() methods that contain only a call to super.setUp().
162JUnitUnnecessaryTearDownChecks for JUnit tearDown() methods that contain only a call to super.tearDown().
163JUnitUnnecessaryThrowsExceptionCheck for throws clauses on JUnit test methods. That is not necessary in Groovy.
164JdbcConnectionReferenceCheck for direct use of java.sql.Connection, which is discouraged and almost never necessary in application code.
165JdbcResultSetReferenceCheck for direct use of java.sql.ResultSet, which is not necessary if using the Groovy Sql facility or an ORM framework such as Hibernate.
166JdbcStatementReferenceCheck for direct use of java.sql.Statement, java.sql.PreparedStatement, or java.sql.CallableStatement, which is not necessary if using the Groovy Sql facility or an ORM framework such as Hibernate.
167LineLengthChecks the maximum length for each line of source code. It checks for number of characters, so lines that include tabs may appear longer than the allowed number when viewing the file. The maximum line length can be configured by setting the length property, which defaults to 120.
168LocaleSetDefaultChecks for calls to Locale.setDefault(), which sets the Locale across the entire JVM.
169LoggerForDifferentClassChecks for instantiating a logger (Log4J, SLF4J, Logback, Apache Commons Logging or Java Util Logging) for a class other than the current class.
170LoggerWithWrongModifiersLogger objects should be declared private, static and final. If subclasses should have access to a Logger in a parent class then the Logger should be declared protected, non-static and final. This rule find loggers that are not declared with these modifiers.
171LoggingSwallowsStacktraceIf you are logging an exception then the proper API is to call error(Object, Throwable), which will log the message and the exception stack trace. If you call error(Object) then the stacktrace may not be logged.
172LongLiteralWithLowerCaseLIn Java and Groovy, you can specify long literals with the L or l character, for instance 55L or 24l. It is best practice to always use an uppercase L and never a lowercase l. This is because 11l rendered in some fonts may look like 111 instead of 11L.
173MethodCountA 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.
174MethodSizeChecks if the size of a method exceeds the number of lines specified by the maxLines property (100).
175MissingBlankLineAfterImportsMakes sure there is a blank line after the imports of a source code file.
176MissingBlankLineAfterPackageMakes sure there is a blank line after the package statement of a source code file.
177MissingNewInThrowStatementA common Groovy mistake when throwing exceptions is to forget the new keyword. For instance, "throw RuntimeException()" instead of "throw new RuntimeException()". If the error path is not unit tested then the production system will throw a Method Missing exception and hide the root cause. This rule finds constructs like "throw RuntimeException()" that look like a new keyword was meant to be used but forgotten.
178MultipleLoggersThis rule catches classes that have more than one logger object defined. Typically, a class has zero or one logger objects.
179MultipleUnaryOperatorsChecks for multiple consecutive unary operators. These are confusing, and are likely typos and bugs.
180NestedBlockDepthChecks for blocks or closures nested more than maxNestedBlockDepth (5) levels deep.
181NestedSynchronizationNested synchronized statements should be avoided. Nested synchronized statements are either useless (if the lock objects are identical) or prone to deadlock.
182NonFinalPublicFieldFinds code that violates secure coding principles for mobile code by declaring a member variable public but not final.
183NonFinalSubclassOfSensitiveInterfaceThe permissions classes such as java.security.Permission and java.security.BasicPermission are designed to be extended. Classes that derive from these permissions classes, however, must prohibit extension. This prohibition ensures that malicious subclasses cannot change the properties of the derived class. Classes that implement sensitive interfaces such as java.security.PrivilegedAction and java.security.PrivilegedActionException must also be declared final for analogous reasons.
184ObjectFinalizeThe finalize() method should only be called by the JVM after the object has been garbage collected.
185ObjectOverrideMisspelledMethodNameVerifies that the names of the most commonly overridden methods of Object: equals, hashCode and toString, are correct.
186PackageNameVerifies that the package name for a class matches a regular expression. By default it checks that the package name consists of only lowercase letters, separated by periods. The regex property specifies the regular expression used to validate the package name. The packageNameRequired property indicates whether a package name declaration is required for all classes.
187ParameterNameVerifies that the name of each parameter matches a regular expression. This rule applies to method parameters, constructor parameters and closure parameters. By default it checks that parameter names start with a lowercase letter and contains only letters or numbers. The regex property specifies the default regular expression used to validate the parameter name. The ignoreParameterNames property (null) can specify parameter names that should be ignored, optionally containing wildcard characters ('*' or '?').
188ParameterReassignmentChecks for a method or closure parameter being reassigned to a new value within the body of the method/closure, which is a confusing and questionable practice. Use a temporary variable instead.
189PrintStackTraceChecks for calls to printStackTrace().
190PrintlnChecks for calls to this.print(), this.println() or this.printf().
191PrivateFieldCouldBeFinalChecks for private fields that are only set within a constructor or field initializer. Such fields can safely be made final.
192PropertyNameVerifies that the name of each property matches a regular expression. By default it checks that property names other than 'static final' start with a lowercase letter and contains only letters or numbers, and 'static final' property names start with an uppercase letter and contain only uppercase letters, numbers and underscores. The regex property specifies the default regular expression used to validate property names. The finalRegex property specifies the regular expression to validate 'final' property names. The staticRegex property specifies the regular expression to validate 'static' property names. The staticFinalRegex property specifies the regular expression to validate 'static final' property names. The ignorePropertyNames property (null) can specify property names that should be ignored, optionally containing wildcard characters ('*' or '?').
193PublicFinalizeMethodCreates a violation when the program violates secure coding principles by declaring a finalize() method public.
194RandomDoubleCoercedToZeroThe 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.
195RemoveAllOnSelfDon'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.
196RequiredRegexChecks for a specified regular expression that must exist within the source code. The regex property specifies the regular expression to check for. It is required and cannot be null or empty.
197RequiredStringChecks for a specified text string that must exist within the source code. The string property specifies the String to check for. It is required and cannot be null or empty.
198ReturnFromFinallyBlockReturning from a finally block is confusing and can hide the original exception.
199ReturnNullFromCatchBlockReturning null from a catch block often masks errors and requires the client to handle error codes. In some coding styles this is discouraged.
200ReturnsNullInsteadOfEmptyArrayConsider returning a zero length array rather than null. It is often a better design to return a length zero array rather than a null reference to indicate that there are no results (i.e., an empty list of results). This way, no explicit check for null is needed by clients of the method.
201ReturnsNullInsteadOfEmptyCollectionConsider returning a zero length collection rather than null. It is often a better design to return a length zero collection rather than a null reference to indicate that there are no results (i.e., an empty list of results). This way, no explicit check for null is needed by clients of the method.
202SerialPersistentFieldsTo use a Serializable object's serialPersistentFields correctly, it must be declared private, static, and final.
203SerialVersionUIDA serialVersionUID is normally intended to be used with Serialization. It needs to be of type long, static, and final. Also, it should have a visibility modifier such as public or private. Providing no modifier creates a Property and Groovy generates a getter, which is probably not intended.
204SerializableClassMustDefineSerialVersionUIDClasses that implement Serializable should define a serialVersionUID. If you don't define serialVersionUID, the system will make one by hashing most of your class's features. Then if you change anything, the UID will change and Java won't let you reload old data.
205SimpleDateFormatMissingLocaleBe sure to specify a Locale when creating a new instance of SimpleDateFormat; the class is locale-sensitive. If you instantiate SimpleDateFormat without a Locale parameter, it will format the date and time according to the default Locale. Both the pattern and the Locale determine the format. For the same pattern, SimpleDateFormat may format a date and time differently if the Locale varies.
206SpaceAfterCatchCheck that there is exactly one space (blank) after the catch keyword and before the opening parenthesis.
207SpaceAfterClosingBraceCheck that there is at least one space (blank) or whitespace after each closing brace ("}") for method/class/interface declarations, closure expressions and block statements.
208SpaceAfterCommaChecks that there is at least one space or whitespace following each comma. That includes checks for method and closure declaration parameter lists, method call parameter lists, Map literals and List literals.
209SpaceAfterForCheck that there is exactly one space (blank) after the for keyword and before the opening parenthesis.
210SpaceAfterIfCheck that there is exactly one space (blank) after the if keyword and before the opening parenthesis.
211SpaceAfterOpeningBraceCheck that there is at least one space (blank) or whitespace after each opening brace ("{") for method/class/interface declarations, closure expressions and block statements.
212SpaceAfterSemicolonChecks that there is at least one space or whitespace following each semicolon separating multiple statements on a single line or the clauses within a classic for loop.
213SpaceAfterSwitchCheck that there is exactly one space (blank) after the switch keyword and before the opening parenthesis.
214SpaceAfterWhileCheck that there is exactly one space (blank) after the while keyword and before the opening parenthesis.
215SpaceAroundClosureArrowChecks that there is whitespace around the closure arrow (->) symbol
216SpaceAroundOperatorCheck that there is at least one space (blank) or whitespace around each binary operator.
217SpaceBeforeClosingBraceCheck that there is at least one space (blank) or whitespace before each closing brace ("}") for method/class/interface declarations, closure expressions and block statements.
218SpaceBeforeOpeningBraceCheck that there is at least one space (blank) or whitespace before each opening brace ("{") for method/class/interface declarations, closure expressions and block statements.
219SpockIgnoreRestUsedIf Spock's @IgnoreRest appears on any method, all non-annotated test methods are not executed. This behaviour is almost always unintended. It's fine to use @IgnoreRest locally during development, but when committing code, it should be removed.
220StatelessClassChecks for fields on classes that should remain "stateless" and reentrant. The ignoreFieldNames property (null) specifies one or more field names that should be ignored. The ignoreFieldTypes property specifies one or more field type names that should be ignored. Both can optionally contain wildcard characters ('*' or '?').
221StatelessSingletonThere is no point in creating a stateless Singleton because there is nothing within the class that needs guarding and no side effects to calling the constructor. Just create new instances of the object or write a Utility class with static methods.
222StaticCalendarFieldCalendar objects should not be used as static fields. Calendars are inherently unsafe for multihtreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application.
223StaticConnectionCreates violations when a java.sql.Connection object is used as a static field. Database connections stored in static fields will be shared between threads, which is unsafe and can lead to race conditions.
224StaticDateFormatFieldDateFormat objects should not be used as static fields. DateFormat are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application.
225StaticMatcherFieldMatcher objects should not be used as static fields. Matcher instances are inherently unsafe for multithreaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application.
226StaticSimpleDateFormatFieldSimpleDateFormat objects should not be used as static fields. SimpleDateFormat are inherently unsafe for multi-threaded use. Sharing a single instance across thread boundaries without proper synchronization will result in erratic behavior of the application.
227SwallowThreadDeathChecks for code that catches ThreadDeath without re-throwing it.
228SynchronizedMethodThis rule reports uses of the synchronized keyword on methods. Synchronized methods are the same as synchronizing on 'this', which effectively make your synchronization policy public and modifiable by other objects. To avoid possibilities of deadlock, it is better to synchronize on internal objects.
229SynchronizedOnBoxedPrimitiveThe code synchronizes on a boxed primitive constant, such as an Integer. Since Integer objects can be cached and shared, this code could be synchronizing on the same object as other, unrelated code, leading to unresponsiveness and possible deadlock
230SynchronizedOnGetClassSynchronization on getClass rather than class literal. This instance method synchronizes on this.getClass(). If this class is subclassed, subclasses will synchronize on the class object for the subclass, which isn't likely what was intended.
231SynchronizedOnReentrantLockSynchronizing on a ReentrantLock field is almost never the intended usage. A ReentrantLock should be obtained using the lock() method and released in a finally block using the unlock() method.
232SynchronizedOnStringSynchronization on a String field can lead to deadlock because Strings are interned by the JVM and can be shared.
233SynchronizedOnThisThis rule reports uses of the synchronized blocks where the synchronization reference is 'this'. Doing this effectively makes your synchronization policy public and modifiable by other objects. To avoid possibilities of deadlock, it is better to synchronize on internal objects.
234SynchronizedReadObjectMethodCatches Serializable classes that define a synchronized readObject method. By definition, an object created by deserialization is only reachable by one thread, and thus there is no need for readObject() to be synchronized. If the readObject() method itself is causing the object to become visible to another thread, that is an example of very dubious coding style.
235SystemErrPrintChecks for calls to System.err.print(), System.err.println() or System.err.printf().
236SystemExitWeb applications should never call System.exit(). A call to System.exit() is probably part of leftover debug code or code imported from a non-J2EE application.
237SystemOutPrintChecks for calls to System.out.print(), System.out.println() or System.out.printf().
238SystemRunFinalizersOnExitMethod calls to System.runFinalizersOnExit() should not be allowed. This method is inherently non-thread-safe, may result in data corruption, deadlock, and may effect parts of the program far removed from it's call point. It is deprecated, and it's use strongly discouraged.
239TernaryCouldBeElvisChecks for ternary expressions where the boolean and true expressions are the same. These can be simplified to an Elvis expression.
240ThisReferenceEscapesConstructorReports constructors passing the 'this' reference to other methods. This equals exposing a half-baked objects and can lead to race conditions during initialization. For reference, see Java Concurrency Gotchas by Alex Miller and Java theory and practice: Safe construction techniques by Brian Goetz.
241ThreadLocalNotStaticFinalThreadLocal fields should be static and final. In the most common case a java.lang.ThreadLocal instance associates state with a thread. A non-static non-final java.lang.ThreadLocal field associates state with an instance-thread combination. This is seldom necessary and often a bug which can cause memory leaks and possibly incorrect behavior.
242ThreadYieldMethod calls to Thread.yield() should not be allowed. This method has no useful guaranteed semantics, and is often used by inexperienced programmers to mask race conditions.
243ThrowErrorChecks for throwing an instance of java.lang.Error.
244ThrowExceptionChecks for throwing an instance of java.lang.Exception.
245ThrowExceptionFromFinallyBlockThrowing an exception from a finally block is confusing and can hide the original exception.
246ThrowNullPointerExceptionChecks for throwing an instance of java.lang.NullPointerException.
247ThrowRuntimeExceptionChecks for throwing an instance of java.lang.RuntimeException.
248ThrowThrowableChecks for throwing an instance of java.lang.Throwable.
249ToStringReturnsNullChecks for toString() methods that return null.
250TrailingWhitespaceChecks that no lines of source code end with whitespace characters.
251UnnecessaryBigDecimalInstantiationIt 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.
252UnnecessaryBigIntegerInstantiationIt is unnecessary to instantiate BigInteger objects. Instead just use the literal with the 'G' identifier to force the type, such as 8G or 42G.
253UnnecessaryBooleanInstantiationUse 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).
254UnnecessaryCallForLastElementThis 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.
255UnnecessaryCallToSubstringCalling String.substring(0) always returns the original string. This code is meaningless.
256UnnecessaryCastChecks for unnecessary cast operations
257UnnecessaryCatchBlockViolations 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.
258UnnecessaryCollectCallSome 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.
259UnnecessaryCollectionCallUseless 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.
260UnnecessaryConstructorThis 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.
261UnnecessaryDefInFieldDeclarationIf 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 = {}.
262UnnecessaryDefInMethodDeclarationIf 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() {}'.
263UnnecessaryDefInVariableDeclarationIf 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'.
264UnnecessaryDotClassTo make a reference to a class, it is unnecessary to specify the '.class' identifier. For instance String.class can be shortened to String.
265UnnecessaryDoubleInstantiationIt 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.
266UnnecessaryElseStatementWhen 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.
267UnnecessaryFailIn a unit test, catching an exception and immediately calling Assert.fail() is pointless and hides the stack trace. It is better to rethrow the exception or not catch the exception at all.
268UnnecessaryFinalOnPrivateMethodA private method is marked final. Private methods cannot be overridden, so marking it final is unnecessary.
269UnnecessaryFloatInstantiationIt 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.
270UnnecessaryGStringString 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.
271UnnecessaryGetterChecks for explicit calls to getter/accessor methods which can, for the most part, be replaced by property access. A getter is defined as a method call that matches get[A-Z] but not getClass() or get[A-Z][A-Z] such as getURL(). Getters do not take method arguments.
272UnnecessaryGroovyImportA 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.
273UnnecessaryIfStatementChecks 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.
274UnnecessaryInstanceOfCheckThis 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.
275UnnecessaryInstantiationToGetClassAvoid instantiating an object just to call getClass() on it; use the .class public member instead.
276UnnecessaryIntegerInstantiationIt is unnecessary to instantiate Integer objects. Instead just use the literal with the 'I' identifier to force the type, such as 8I or 42i.
277UnnecessaryLongInstantiationIt is unnecessary to instantiate Long objects. Instead just use the literal with the 'L' identifier to force the type, such as 8L or 42L.
278UnnecessaryModOneAny 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).
279UnnecessaryNullCheckGroovy contains the safe dereference operator, which can be used in boolean conditional statements to safely replace explicit "x == null" tests.
280UnnecessaryNullCheckBeforeInstanceOfThere is no need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.
281UnnecessaryObjectReferencesViolations 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.
282UnnecessaryOverridingMethodThe overriding method merely calls the same method defined in a superclass
283UnnecessaryPackageReferenceChecks for explicit package reference for classes that Groovy imports by default, such as java.lang.String, java.util.Map and groovy.lang.Closure.
284UnnecessaryParenthesesForMethodCallWithClosureIf 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.
285UnnecessaryPublicModifierThe 'public' modifier is not required on methods or classes.
286UnnecessaryReturnKeywordIn 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.
287UnnecessarySelfAssignmentMethod contains a pointless self-assignment to a variable or property.
288UnnecessarySemicolonSemicolons 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.
289UnnecessaryStringInstantiationUse a String literal (e.g., "...") instead of calling the corresponding String constructor (new String("..")) directly.
290UnnecessarySubstringThis 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].
291UnnecessaryTernaryExpressionChecks 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.
292UnnecessaryToStringChecks for unnecessary calls to toString().
293UnnecessaryTransientModifierThe field is marked as transient, but the class isn't Serializable, so marking it as transient has no effect.
294UnsafeArrayDeclarationTriggers a violation when an array is declared public, final, and static. Secure coding principles state that, in most cases, an array declared public, final and static is a bug because arrays are mutable objects.
295UnsafeImplementationAsMapReports incomplete interface implementations created by map-to-interface coercions. Example: [hasNext: { ... }] as Iterator (Not all Iterator methods are implemented. An UnsupportedOperationException will be thrown upon call to e.g. next().) By default, this rule does not apply to test files.
296UnusedArrayChecks for array allocations that are not assigned or used, unless it is the last statement within a block.
297UnusedImportImports for a class that is never referenced within the source file is unnecessary.
298UnusedMethodParameterThis rule finds instances of method parameters not being used. It does not analyze private methods (that is done by the UnusedPrivateMethodParameter rule) or methods marked @Override.
299UnusedObjectChecks for object allocations that are not assigned or used, unless it is the last statement within a block
300UnusedPrivateFieldChecks for private fields that are not referenced within the same class.
301UnusedPrivateMethodChecks for private methods that are not referenced within the same class.
302UnusedPrivateMethodParameterChecks for parameters to private methods that are not referenced within the method body.
303UnusedVariableChecks for variables that are never referenced. The ignoreVariableNames property (null) specifies one or more variable names that should be ignored, optionally containing wildcard characters ('*' or '?').
304UseAssertEqualsInsteadOfAssertTrueThis rule detects JUnit assertions in object equality. These assertions should be made by more specific methods, like assertEquals.
305UseAssertFalseInsteadOfNegationIn unit tests, if a condition is expected to be false then there is no sense using assertTrue with the negation operator. For instance, assertTrue(!condition) can always be simplified to assertFalse(condition)
306UseAssertNullInsteadOfAssertEqualsThis rule detects JUnit calling assertEquals where the first or second parameter is null. These assertion should be made against the assertNull method instead.
307UseAssertSameInsteadOfAssertTrueThis rule detects JUnit calling assertTrue where the first or second parameter is an Object#is() call testing for reference equality. These assertion should be made against the assertSame method instead.
308UseAssertTrueInsteadOfAssertEqualsThis rule detects JUnit calling assertEquals where the first parameter is a boolean. These assertions should be made by more specific methods, like assertTrue or assertFalse.
309UseAssertTrueInsteadOfNegationIn unit tests, if a condition is expected to be true then there is no sense using assertFalse with the negation operator. For instance, assertFalse(!condition) can always be simplified to assertTrue(condition)
310UseCollectManyIn many case collectMany() yields the same result as collect{}.flatten(). It is easier to understand and more clearly conveys the intent.
311UseCollectNestedInstead of nested collect{}-calls use collectNested{}
312UseOfNotifyMethodThis code calls notify() rather than notifyAll(). Java monitors are often used for multiple conditions. Calling notify() only wakes up one thread, meaning that the thread woken up might not be the one waiting for the condition that the caller just satisfied.
313VectorIsObsoleteThe java.util.Vector class is effectively obsolete. Use the Java Collections Framework classes instead, including ArrayList or Collections.synchronizedList(). See the JDK javadoc.
314VolatileArrayFieldVolatile array fields are unsafe because the contents of the array are not treated as volatile. Changing the entire array reference is visible to other threads, but changing an array element is not.
315VolatileLongOrDoubleFieldLong or double fields should not be declared as volatile. Java specifies that reads and writes from such fields are atomic, but many JVM's have violated this specification. Unless you are certain of your JVM, it is better to synchronize access to such fields rather than declare them volatile. This rule flags fields marked volatile when their type is double or long or the name of their type is "Double" or "Long".
316WaitOutsideOfWhileLoopCalls to Object.wait() must be within a while loop. Consider using the Java concurrency utilities instead of wait() and notify().
317WhileStatementBracesUse braces for while statements, even for a single statement.