CodeNarc Report

Report title:
Date:Apr 3, 2013 4:52:38 PM
Generated with:CodeNarc v0.17

Summary by Package

PackageTotal FilesFiles with ViolationsPriority 1Priority 2Priority 3
All Packages3224-11710
org/k1s/cpn/nppn/att31-271
org/k1s/cpn/nppn/pragmatics54-135
org/k1s/nppn22-7-
org/k1s/nppn/generation76-243
org/k1s/nppn/cpn/io11-7-
org/k1s/nppn/blocks74-81
org/k1s/nppn/blocks/derived32-21-
org/k1s/nppn/generationVisitors44-10-

Package: org.k1s.cpn.nppn.att

➥ ATTFactory.groovy

Rule NamePriorityLine #Source Line / Message
IfStatementBraces235

[SRC]if(it.controlFlow || it.block != null) controlFlowPragma..s << it.name

[MSG]The if statement lacks braces

FactoryMethodName248

[SRC]AbstractTemplateTree createATT(pn, pragmatics, bindings){

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

DuplicateStringLiteral289

[SRC]page.object.findAll{ it instanceof Place && !it.pragmati..ch{ state ->

[MSG]Duplicate String Literal: LCV

IfStatementBraces2106

[SRC]if(page.id == subPageID)

[MSG]The if statement lacks braces

DuplicateStringLiteral2137

[SRC]atomic.pragmatics = service.start_node.pragmatics.findAl..= "service"}

[MSG]Duplicate String Literal: service

IfStatementBraces2142

[SRC]if(firstBlockStart.size() == 0) return service

[MSG]The if statement lacks braces

IfStatementBraces2144

[SRC]if(firstBlockStart.size() > 1) throw new Exception("unex..rt.size()}")

[MSG]The if statement lacks braces

LineLength2144

[SRC]if(firstBlockStart.size() > 1) throw new Exception("unex..rt.size()}")

[MSG]The line exceeds 120 characters. The line is 151 characters.

ThrowException2144

[SRC]if(firstBlockStart.size() > 1) throw new Exception("unex..rt.size()}")

[MSG]The type Exception should not be thrown

IfStatementBraces2150

[SRC]if(block != null) service.children << block

[MSG]The if statement lacks braces

IfStatementBraces2153

[SRC]if(block != null) service.children << block

[MSG]The if statement lacks braces

IfStatementBraces2168

[SRC]if(isControllFlowPlace(it.target)) retval << it.target

[MSG]The if statement lacks braces

IfStatementBraces2181

[SRC]if(controlFlowPragmatics.contains(it.name)) retval = true

[MSG]The if statement lacks braces

IfStatementBraces2196

[SRC]if(pragmaticsMap[it.name].block != null) retval = true

[MSG]The if statement lacks braces

EmptyElseBlock2217

[SRC]} else {

[MSG]The else block is empty

FactoryMethodName2234

[SRC]def createBlock(Place node, parent){

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

IfStatementBraces2248

[SRC]if(block != null) sequence.children << block

[MSG]The if statement lacks braces

IfStatementBraces2258

[SRC]if(block != null) sequence.children << block

[MSG]The if statement lacks braces

ThrowException2270

[SRC]throw new Exception("branching not yet supported")

[MSG]The type Exception should not be thrown

ThrowException2272

[SRC]throw new Exception("block type for ${node.name} not yet supported")

[MSG]The type Exception should not be thrown

FactoryMethodName2281

[SRC]def createAtomic(Place node, parent, transition = null){

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

LineLength2282

[SRC]//if(node.sourceArc.size() != 1) throw new Exception("No..xpected 1.")

[MSG]The line exceeds 120 characters. The line is 162 characters.

IfStatementBraces2298

[SRC]if(transition == null) return null

[MSG]The if statement lacks braces

DuplicateStringLiteral2315

[SRC]def res = findNodesInPageByPragmatic(page, "service")

[MSG]Duplicate String Literal: service

ThrowException2317

[SRC]throw new Exception("Too many services in $page : $res")

[MSG]The type Exception should not be thrown

ThrowException2320

[SRC]throw new Exception("No service found $page")

[MSG]The type Exception should not be thrown

ThrowException2335

[SRC]throw new Exception("Too many returns in $page")

[MSG]The type Exception should not be thrown

ParameterReassignment3294

[SRC]transition = it.target

[MSG]The method parameter [transition] in class org.k1s.cpn.nppn.att.ATTFactory was reassigned. Use a temporary variable instead.

Package: org.k1s.petriCode.pragmatics

➥ PrgamaticsDescriptorDSL.groovy

Rule NamePriorityLine #Source Line / Message
FactoryMethodName221

[SRC]def build(closure){

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

IfStatementBraces225

[SRC]if(!(closure instanceof Closure)) throw new IllegalArgum..: $closure")

[MSG]The if statement lacks braces

ParameterReassignment323

[SRC]closure = new GroovyShell().evaluate("return {${closure}}")

[MSG]The method parameter [closure] in class org.k1s.petriCode.pragmatics.PrgamaticsDescriptorDSL was reassigned. Use a temporary variable instead.

➥ Pragmatics.groovy

Rule NamePriorityLine #Source Line / Message
DuplicateStringLiteral248

[SRC]prag.name = pragDef.subSequence(0, pragDef.indexOf('('))

[MSG]Duplicate String Literal: (

DuplicateStringLiteral251

[SRC]String d = pragDef.substring(pragDef.indexOf('(') + 1,

[MSG]Duplicate String Literal: (

➥ PragmaticsDescriptor.groovy

Rule NamePriorityLine #Source Line / Message
ThrowException250

[SRC]throw new Exception("can not construct PragmaticConstrai..${c.class}")

[MSG]The type Exception should not be thrown

ParameterReassignment329

[SRC]origin = OriginType.EXPLICIT

[MSG]The method parameter [origin] in class org.k1s.petriCode.pragmatics.PragmaticsDescriptor was reassigned. Use a temporary variable instead.

ParameterReassignment331

[SRC]origin = OriginType.DERIVED

[MSG]The method parameter [origin] in class org.k1s.petriCode.pragmatics.PragmaticsDescriptor was reassigned. Use a temporary variable instead.

➥ PragmaticsChecker.groovy

Rule NamePriorityLine #Source Line / Message
EmptyIfStatement299

[SRC]if(desc && desc.constraints instanceof List){

[MSG]The if statement is empty

DuplicateStringLiteral2112

[SRC]println "not ok"

[MSG]Duplicate String Literal: not ok

DuplicateStringLiteral2115

[SRC]println "ok"

[MSG]Duplicate String Literal: ok

DeadCode2151

[SRC]break

[MSG]This code cannot be reached

DeadCode2154

[SRC]break

[MSG]This code cannot be reached

DeadCode2159

[SRC]break

[MSG]This code cannot be reached

ThrowException2161

[SRC]throw new Exception("unknown node type: $typeStr")

[MSG]The type Exception should not be thrown

ThrowException2186

[SRC]throw new Exception("unknown level name: ${levelName}")

[MSG]The type Exception should not be thrown

InvertedIfElse3104

[SRC]if(!PragmaticsChecker.checkConnectedType(desc.constraint..ypes, obj)){

[MSG]Testing the negative condition first can make an if statement confusing

InvertedIfElse3111

[SRC]if(!PragmaticsChecker.checklevel(desc.constraints.levels, pageType)){

[MSG]Testing the negative condition first can make an if statement confusing

Package: org.k1s.nppn

Package: org.k1s.nppn.generation

➥ Binding.groovy

Rule NamePriorityLine #Source Line / Message
IfStatementBraces223

[SRC]if(template instanceof Closure) return template.call()

[MSG]The if statement lacks braces

➥ TemplateManager.groovy

Rule NamePriorityLine #Source Line / Message
IfStatementBraces227

[SRC]if(template instanceof String)

[MSG]The if statement lacks braces

IfStatementBraces230

[SRC]if(template instanceof Closure)

[MSG]The if statement lacks braces

ThrowRuntimeException233

[SRC]throw new RuntimeException("could not find specified tem...toString())

[MSG]The type RuntimeException should not be thrown

➥ Conditionals.groovy

Rule NamePriorityLine #Source Line / Message
IfStatementBraces2112

[SRC]if(currExpr != null) parentExprs.push(currExpr)

[MSG]The if statement lacks braces

DuplicateStringLiteral2125

[SRC]}else if(it == ' '){

[MSG]Duplicate String Literal:

IfStatementBraces2129

[SRC]if(currToken.trim().size() > 0)

[MSG]The if statement lacks braces

DuplicateStringLiteral2153

[SRC]if(it == '(' && currCond == null){

[MSG]Duplicate String Literal: (

DuplicateStringLiteral2156

[SRC]}else if(it == '(') {

[MSG]Duplicate String Literal: (

DuplicateStringLiteral2158

[SRC]} else if(it == ')'){

[MSG]Duplicate String Literal: )

DuplicateStringLiteral2171

[SRC]}else if(it == ' ' && state == COND){

[MSG]Duplicate String Literal:

IfStatementBraces2172

[SRC]if(currCond.e == null) currCond.e = currToken

[MSG]The if statement lacks braces

ElseBlockBraces2172

[SRC]if(currCond.e == null) currCond.e = currToken

[MSG]The else block lacks braces

➥ TemplateParameters.groovy

Rule NamePriorityLine #Source Line / Message
IfStatementBraces226

[SRC]if(strategy == null) strategy = TemplateParameters.DEFAULT_STRATEGY

[MSG]The if statement lacks braces

ThrowException236

[SRC]throw new Exception("Unimplemented parameter strategy: $strategy")

[MSG]The type Exception should not be thrown

DuplicateStringLiteral256

[SRC]def pragParams = prag.arguments.split(",")

[MSG]Duplicate String Literal: ,

DuplicateStringLiteral268

[SRC]retval['condTrueExpr'] = pragParams[1].replaceAll("_",",").trim()

[MSG]Duplicate String Literal: ,

DuplicateStringLiteral269

[SRC]retval['condFalseExpr'] = pragParams[2].replaceAll("_",",").trim()

[MSG]Duplicate String Literal: _

DuplicateStringLiteral269

[SRC]retval['condFalseExpr'] = pragParams[2].replaceAll("_",",").trim()

[MSG]Duplicate String Literal: ,

ParameterReassignment326

[SRC]if(strategy == null) strategy = TemplateParameters.DEFAULT_STRATEGY

[MSG]The method parameter [strategy] in class org.k1s.nppn.generation.TemplateParameters was reassigned. Use a temporary variable instead.

➥ BindingsDSL.groovy

Rule NamePriorityLine #Source Line / Message
PropertyName236

[SRC]static final String postfix = "\n)"

[MSG]The property name postfix in class org.k1s.nppn.generation.BindingsDSL does not match the pattern [A-Z][A-Z0-9_]*

DuplicateStringLiteral283

[SRC]} else if(style == "BINDINGS"){

[MSG]Duplicate String Literal: BINDINGS

➥ CodeGenerator.groovy

Rule NamePriorityLine #Source Line / Message
DuplicateStringLiteral269

[SRC]text = text.replace("%%yield_declarations%%", node.decla..ls found*/")

[MSG]Duplicate String Literal: %%yield_declarations%%

IfStatementBraces276

[SRC]if(str.indexOf("<") < 0) return str

[MSG]The if statement lacks braces

DuplicateStringLiteral278

[SRC]return str.substring(0,str.indexOf("<")).trim()

[MSG]Duplicate String Literal: <

ParameterReassignment382

[SRC]str = removePrags(str)

[MSG]The method parameter [str] in class org.k1s.nppn.generation.CodeGenerator was reassigned. Use a temporary variable instead.

ParameterReassignment383

[SRC]str = str.replace(" ", "_")

[MSG]The method parameter [str] in class org.k1s.nppn.generation.CodeGenerator was reassigned. Use a temporary variable instead.

Package: org.k1s.nppn.cpn.io

➥ CpnIO.groovy

Rule NamePriorityLine #Source Line / Message
CatchException240

[SRC]} catch (Exception e) {

[MSG]The type Exception should not be caught

ThrowRuntimeException243

[SRC]throw new RuntimeException(e);

[MSG]The type RuntimeException should not be thrown

IfStatementBraces289

[SRC]if(elemName == null) return retval;

[MSG]The if statement lacks braces

DuplicateStringLiteral295

[SRC]int pragStart = elemName.indexOf("<<", start) + 2;

[MSG]Duplicate String Literal: <<

IfStatementBraces2100

[SRC]if(!pragDef.contains("(")) pragDef = pragDef + "()";

[MSG]The if statement lacks braces

CatchException2105

[SRC]}catch(Exception ex){

[MSG]The type Exception should not be caught

ThrowException2106

[SRC]throw new Exception("Unnable to parse $elemName",ex)

[MSG]The type Exception should not be thrown

➥ Conditionals.groovy

Rule NamePriorityLine #Source Line / Message
IfStatementBraces217

[SRC]if(!cond) work()

[MSG]The if statement lacks braces

Package: org.k1s.nppn.blocks

➥ Atomic.groovy

Rule NamePriorityLine #Source Line / Message
TernaryCouldBeElvis336

[SRC]text.append tm.runTemplate(binding.template,params ? params : [:])

[MSG](params) ? params : [:] in class org.k1s.nppn.blocks.Atomic can be simplified to params ?: [:]

Package: org.k1s.nppn.blocks.derived

➥ PNPattern.groovy

Rule NamePriorityLine #Source Line / Message
IfStatementBraces245

[SRC]if(type != null)

[MSG]The if statement lacks braces

EmptyIfStatement252

[SRC]if(node instanceof Arc){

[MSG]The if statement is empty

IfStatementBraces258

[SRC]if(name != node.name.text) return false

[MSG]The if statement lacks braces

IfStatementBraces269

[SRC]if(pragNode == null || pragNode.pragmatics == null || pr..return false

[MSG]The if statement lacks braces

IfStatementBraces275

[SRC]if(!pragmatics.contains(pragName)) pragsOk = false

[MSG]The if statement lacks braces

IfStatementBraces277

[SRC]if(!pragsOk) return false

[MSG]The if statement lacks braces

IfStatementBraces281

[SRC]if(node instanceof Page) return false

[MSG]The if statement lacks braces

IfStatementBraces288

[SRC]if(adjPattern.matchNode(adjArc.target)) hasMatchingAdj = true

[MSG]The if statement lacks braces

IfStatementBraces291

[SRC]if(!hasMatchingAdj) adjOk = false

[MSG]The if statement lacks braces

IfStatementBraces295

[SRC]if(!adjOk) return false

[MSG]The if statement lacks braces

IfStatementBraces2120

[SRC]if(node.getTargetArc().size() < minInEdges) return false

[MSG]The if statement lacks braces

IfStatementBraces2125

[SRC]if(node.getSourceArc().size() < minOutEdges) return false

[MSG]The if statement lacks braces

IfStatementBraces2129

[SRC]if(node instanceof Page) return false

[MSG]The if statement lacks braces

IfStatementBraces2155

[SRC]if(arc.target == to) retval = true

[MSG]The if statement lacks braces

IfStatementBraces2170

[SRC]if(linksTo.contains(it.target)) numLinks++

[MSG]The if statement lacks braces

➥ PragmaticsDerivator.groovy

Rule NamePriorityLine #Source Line / Message
PropertyName220

[SRC]static CONTROL_FLOW_PRAGS = ["Id", "startLoop", "endLoop..h", "merge"]

[MSG]The property name CONTROL_FLOW_PRAGS in class org.k1s.nppn.blocks.derived.PragmaticsDerivator does not match the pattern [a-z][a-zA-Z0-9]*

IfStatementBraces274

[SRC]if(serviceNode == null) throw new IllegalArgumentExcepti..no service")

[MSG]The if statement lacks braces

LineLength2104

[SRC]PNPattern pd = new GroovyShell(this.getClass().getClassL..ttern; $it")

[MSG]The line exceeds 120 characters. The line is 130 characters.

DuplicateStringLiteral2134

[SRC]def serviceNode = page.object.findAll{ it.pragmatics.nam.."service") }

[MSG]Duplicate String Literal: service

IfStatementBraces2135

[SRC]if(serviceNode.size() != 1) throw new Exception("Illegal..rviceNode}")

[MSG]The if statement lacks braces

ThrowException2135

[SRC]if(serviceNode.size() != 1) throw new Exception("Illegal..rviceNode}")

[MSG]The type Exception should not be thrown

➥ Principal.groovy

Rule NamePriorityLine #Source Line / Message
LineLength241

[SRC]this.text = new TemplateManager().runTemplate(binding.te..).toString()

[MSG]The line exceeds 120 characters. The line is 152 characters.

➥ Service.groovy

Rule NamePriorityLine #Source Line / Message
PropertyName215

[SRC]def start_node

[MSG]The property name start_node in class org.k1s.nppn.blocks.Service does not match the pattern [a-z][a-zA-Z0-9]*

PropertyName216

[SRC]def end_node

[MSG]The property name end_node in class org.k1s.nppn.blocks.Service does not match the pattern [a-z][a-zA-Z0-9]*

➥ Block.groovy

Rule NamePriorityLine #Source Line / Message
AbstractClassWithoutAbstractMethod28

[SRC]abstract class Block {

[MSG]The abstract class org.k1s.nppn.blocks.Block contains no abstract methods

PublicInstanceField29

[SRC]public def start

[MSG]Violation in class org.k1s.nppn.blocks.Block. Using public fields is considered bad design. Create property 'start' instead.

PublicInstanceField210

[SRC]public def end

[MSG]Violation in class org.k1s.nppn.blocks.Block. Using public fields is considered bad design. Create property 'end' instead.

PublicInstanceField212

[SRC]public def text

[MSG]Violation in class org.k1s.nppn.blocks.Block. Using public fields is considered bad design. Create property 'text' instead.

PublicInstanceField213

[SRC]public def pragmatics = []

[MSG]Violation in class org.k1s.nppn.blocks.Block. Using public fields is considered bad design. Create property 'pragmatics' instead.

➥ NPPN.groovy

Rule NamePriorityLine #Source Line / Message
ThrowException269

[SRC]throw new Exception("nyi")

[MSG]The type Exception should not be thrown

DuplicateStringLiteral2105

[SRC]_(longOpt: 'no-derived', 'No derived pragmatics will be added')

[MSG]Duplicate String Literal: no-derived

DuplicateStringLiteral2106

[SRC]_(longOpt: 'output-annotated-net', 'write the annotated ..output dir')

[MSG]Duplicate String Literal: output-annotated-net

DuplicateStringLiteral2107

[SRC]_(longOpt: 'only-output-annotated-net','write the annota..r and exit')

[MSG]Duplicate String Literal: only-output-annotated-net

LineLength2108

[SRC]//p(longOpt: 'pragmatics-specification', args: Option.UN.. the model')

[MSG]The line exceeds 120 characters. The line is 157 characters.

DuplicateStringLiteral2110

[SRC]c(longOpt: 'no-core-pragmatics', 'disables the default c..roagmatics')

[MSG]Duplicate String Literal: no-core-pragmatics

Package: org.k1s.nppn.generationVisitors

➥ ODGVisitor.groovy

Rule NamePriorityLine #Source Line / Message
PackageName2

[MSG]package=org.k1s.nppn.generationVisitors

PropertyName216

[SRC]static final def visitorsPass1 = [new GenerationVisitor(),

[MSG]The property name visitorsPass1 in class org.k1s.nppn.generationVisitors.ODGVisitor does not match the pattern [A-Z][A-Z0-9_]*

PropertyName219

[SRC]static final def visitorsPass2 = [new VarsTextVisitor()]

[MSG]The property name visitorsPass2 in class org.k1s.nppn.generationVisitors.ODGVisitor does not match the pattern [A-Z][A-Z0-9_]*

IfStatementBraces253

[SRC]if(it != null) flattenAtt(it, list)

[MSG]The if statement lacks braces

➥ GenerationVisitor.groovy

Rule NamePriorityLine #Source Line / Message
PackageName2

[MSG]package=org.k1s.nppn.generationVisitors

➥ VarsTextVisitor.groovy

Rule NamePriorityLine #Source Line / Message
PackageName2

[MSG]package=org.k1s.nppn.generationVisitors

➥ VarsVisitor.groovy

Rule NamePriorityLine #Source Line / Message
PackageName2

[MSG]package=org.k1s.nppn.generationVisitors

LineLength227

[SRC]//println "element.metaClass.hasProperty(element, \"pare..uch field'}"

[MSG]The line exceeds 120 characters. The line is 223 characters.

IfStatementBraces239

[SRC]if(vars > -1 ) vars = vars + 7

[MSG]The if statement lacks braces

ElseBlockBraces239

[SRC]if(vars > -1 ) vars = vars + 7

[MSG]The else block lacks braces

Rule Descriptions

#Rule NameDescription
1AbstractClassNameVerifies 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.
2AbstractClassWithPublicConstructorChecks for abstract classes that define a public constructor, which is useless and confusing.
3AbstractClassWithoutAbstractMethodThe 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.
4AssertWithinFinallyBlockChecks for assert statements within a finally block. An assert can throw an exception, hiding the original exception, if there is one.
5AssignCollectionSortThe 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.
6AssignCollectionUniqueThe 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.
7AssignmentInConditionalAn assignment operator (=) was used in a conditional test. This is usually a typo, and the comparison operator (==) was intended.
8BigDecimalInstantiationChecks for calls to the BigDecimal constructors that take a double parameter, which may result in an unexpected BigDecimal value.
9BitwiseOperatorInConditionalChecks for bitwise operations in conditionals, if you need to do a bitwise operation then it is best practive to extract a temp variable.
10BooleanGetBooleanThis 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'].
11BooleanMethodReturnsNullMethod 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.
12BracesForClassChecks 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.
13BracesForForLoopChecks 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.
14BracesForIfElseChecks 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.
15BracesForMethodChecks 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.
16BracesForTryCatchFinallyChecks 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.
17BrokenNullCheckLooks for faulty checks for null that can cause a NullPointerException.
18BrokenOddnessCheckThe 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.
19BuilderMethodWithSideEffectsA 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.
20CatchArrayIndexOutOfBoundsExceptionCheck the size of the array before accessing an array element rather than catching ArrayIndexOutOfBoundsException.
21CatchErrorCatching Error is dangerous; it can catch exceptions such as ThreadDeath and OutOfMemoryError.
22CatchExceptionCatching Exception is often too broad or general. It should usually be restricted to framework or infrastructure code, rather than application code.
23CatchIllegalMonitorStateExceptionDubious 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).
24CatchIndexOutOfBoundsExceptionCheck that an index is valid before accessing an indexed element rather than catching IndexOutOfBoundsException.
25CatchNullPointerExceptionCatching NullPointerException is never appropriate. It should be avoided in the first place with proper null checking, and it can mask underlying errors.
26CatchRuntimeExceptionCatching RuntimeException is often too broad or general. It should usually be restricted to framework or infrastructure code, rather than application code.
27CatchThrowableCatching Throwable is dangerous; it can catch exceptions such as ThreadDeath and OutOfMemoryError.
28ClassForNameUsing 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.
29ClassJavadocMakes sure each class and interface definition is preceded by javadoc. Enum definitions are not checked, due to strange behavior in the Groovy AST.
30ClassNameVerifies 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.
31CloneableWithoutCloneA class that implements java.lang.Cloneable should define a clone() method.
32CloseWithoutCloseableIf a class defines a "void close()" then that class should implement java.io.Closeable.
33ClosureAsLastMethodParameterIf a method is called and the last parameter is an inline closure then it can be declared outside of the method call brackets.
34CollectAllIsDeprecatedcollectAll{} is deprecated since Groovy 1.8.1. Use collectNested instead{}.
35CompareToWithoutComparableIf 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.
36ComparisonOfTwoConstantsChecks 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].
37ComparisonWithSelfChecks 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.
38ConfusingClassNamedExceptionThis class is not derived from another exception, but ends with 'Exception'. This will be confusing to users of this class.
39ConfusingMethodNameChecks 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.
40ConfusingMultipleReturnsMultiple 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.
41ConfusingTernaryIn 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?".
42ConstantAssertExpressionChecks for assert statements where the assert boolean condition expression is a constant or literal value.
43ConstantIfExpressionChecks for if statements with a constant value for the if expression, such as true, false, null, or a literal constant value.
44ConstantTernaryExpressionChecks for ternary expressions with a constant value for the boolean expression, such as true, false, null, or a literal constant value.
45ConstantsOnlyInterfaceAn 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.
46CouldBeElvisCatch an if block that could be written as an elvis expression.
47DeadCodeDead 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.
48DoubleNegativeThere 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.
49DuplicateCaseStatementCheck for duplicate case statements in a switch block, such as two equal integers or strings.
50DuplicateListLiteralCode containing duplicate List literals can usually be improved by declaring the List as a constant field.
51DuplicateMapKeyA map literal is created with duplicated key. The map entry will be overwritten.
52DuplicateMapLiteralCode containing duplicate Map literals can usually be improved by declaring the Map as a constant field.
53DuplicateNumberLiteralCode containing number String literals can usually be improved by declaring the number as a constant field. The ignoreNumbers property (0,1) can optionally specify a comma-separated list of numbers to ignore.
54DuplicateSetValueA Set literal is created with duplicate constant value. A set cannot contain two elements with the same value.
55DuplicateStringLiteralCode containing duplicate String literals can usually be improved by declaring the String as a constant field. The ignoreStrings property () can optionally specify a comma-separated list of Strings to ignore.
56ElseBlockBracesUse 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.
57EmptyCatchBlockIn most cases, exceptions should not be caught and ignored (swallowed).
58EmptyElseBlockEmpty else blocks are confusing and serve no purpose.
59EmptyFinallyBlockEmpty finally blocks are confusing and serve no purpose.
60EmptyForStatementEmpty for statements are confusing and serve no purpose.
61EmptyIfStatementEmpty if statements are confusing and serve no purpose.
62EmptyInstanceInitializerAn empty class instance initializer was found. It is safe to remove it.
63EmptyMethodA method was found without an implementation. If the method is overriding or implementing a parent method, then mark it with the @Override annotation.
64EmptyMethodInAbstractClassAn empty method in an abstract class should be abstract instead, as developer may rely on this empty implementation rather than code the appropriate one.
65EmptyStaticInitializerAn empty static initializer was found. It is safe to remove it.
66EmptySwitchStatementEmpty switch statements are confusing and serve no purpose.
67EmptySynchronizedStatementEmpty synchronized statements are confusing and serve no purpose.
68EmptyTryBlockEmpty try blocks are confusing and serve no purpose.
69EmptyWhileStatementEmpty while statements are confusing and serve no purpose.
70EqualsAndHashCodeIf either the boolean equals(Object) or the int hashCode() methods are overridden within a class, then both must be overridden.
71EqualsOverloadedThe 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.
72ExceptionExtendsErrorErrors are system exceptions. Do not extend them.
73ExplicitArrayListInstantiationThis 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.
74ExplicitCallToAndMethodThis 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
75ExplicitCallToCompareToMethodThis 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.
76ExplicitCallToDivMethodThis 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
77ExplicitCallToEqualsMethodThis 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
78ExplicitCallToGetAtMethodThis 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]
79ExplicitCallToLeftShiftMethodThis 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
80ExplicitCallToMinusMethodThis 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
81ExplicitCallToModMethodThis 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
82ExplicitCallToMultiplyMethodThis 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
83ExplicitCallToOrMethodThis 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
84ExplicitCallToPlusMethodThis 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
85ExplicitCallToPowerMethodThis 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
86ExplicitCallToRightShiftMethodThis 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
87ExplicitCallToXorMethodThis 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
88ExplicitGarbageCollectionCalls 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.
89ExplicitHashMapInstantiationThis 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.
90ExplicitHashSetInstantiationThis 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.
91ExplicitLinkedHashMapInstantiationThis 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.
92ExplicitLinkedListInstantiationThis 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.
93ExplicitStackInstantiationThis 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.
94ExplicitTreeSetInstantiationThis 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.
95FactoryMethodNameA 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'.
96FieldNameVerifies 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 (null)can specify field names that should be ignored, optionally containing wildcard characters ('*' or '?').
97FinalClassWithProtectedMemberThis 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.
98ForLoopShouldBeWhileLoopA for loop without an init and update statement can be simplified to a while loop.
99ForStatementBracesUse braces for for statements, even for a single statement.
100GStringAsMapKeyA GString should not be used as a map key since its hashcode is not guaranteed to be stable. Consider calling key.toString().
101GetterMethodCouldBePropertyIf 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.
102GroovyLangImmutableThe groovy.lang.Immutable annotation has been deprecated and replaced by groovy.transform.Immutable. Do not use the Immutable in groovy.lang.
103HardCodedWindowsFileSeparatorThis 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.
104HardCodedWindowsRootDirectoryThis 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.
105HashtableIsObsoleteThe java.util.Hashtable class is effectively obsolete. Use the Java Collections Framework classes instead, including HashMap or ConcurrentHashMap. See the JDK javadoc.
106IfStatementBracesUse braces for if statements, even for a single statement.
107ImplementationAsTypeChecks 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.
108IntegerGetIntegerThis 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'].
109InterfaceNameVerifies 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.
110InvertedIfElseAn 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.
111LineLengthChecks 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.
112LongLiteralWithLowerCaseLIn 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.
113MethodNameVerifies that the name of each method matches a regular expression. By default it checks that the method name starts with a lowercase letter. The regex property specifies the regular expression to check the method name against. The ignoreMethodNames property (null) can specify method names that should be ignored, optionally containing wildcard characters ('*' or '?').
114MissingNewInThrowStatementA 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.
115ObjectOverrideMisspelledMethodNameVerifies that the names of the most commonly overridden methods of Object: equals, hashCode and toString, are correct.
116PackageNameVerifies 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.
117ParameterNameVerifies 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 '?').
118ParameterReassignmentChecks 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.
119PrivateFieldCouldBeFinalChecks for private fields that are only set within a constructor or field initializer. Such fields can safely be made final.
120PropertyNameVerifies 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 '?').
121PublicInstanceFieldUsing public fields is considered to be a bad design. Use properties instead.
122RandomDoubleCoercedToZeroThe 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.
123RemoveAllOnSelfDon'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.
124ReturnFromFinallyBlockReturning from a finally block is confusing and can hide the original exception.
125ReturnNullFromCatchBlockReturning null from a catch block often masks errors and requires the client to handle error codes. In some coding styles this is discouraged.
126ReturnsNullInsteadOfEmptyArrayConsider 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.
127ReturnsNullInsteadOfEmptyCollectionConsider 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.
128SimpleDateFormatMissingLocaleBe 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.
129StatelessSingletonThere 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.
130SwallowThreadDeathChecks for code that catches ThreadDeath without re-throwing it.
131TernaryCouldBeElvisChecks for ternary expressions where the boolean and true expressions are the same. These can be simplified to an Elvis expression.
132ThrowErrorChecks for throwing an instance of java.lang.Error.
133ThrowExceptionChecks for throwing an instance of java.lang.Exception.
134ThrowExceptionFromFinallyBlockThrowing an exception from a finally block is confusing and can hide the original exception.
135ThrowNullPointerExceptionChecks for throwing an instance of java.lang.NullPointerException.
136ThrowRuntimeExceptionChecks for throwing an instance of java.lang.RuntimeException.
137ThrowThrowableChecks for throwing an instance of java.lang.Throwable.
138UseCollectManyIn many case collectMany() yields the same result as collect{}.flatten(). It is easier to understand and more clearly conveys the intent.
139UseCollectNestedInstead of nested collect{}-calls use collectNested{}
140VariableNameVerifies that the name of each method matches a regular expression. By default it checks that non-'final' variable names start with a lowercase letter and contains only letters or numbers, and 'final' variable 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 a non-'final' variable name. The finalRegex property specifies the regular expression used to validate 'final' variable names. The ignoreVariableNames property (null) can specify variable names that should be ignored, optionally containing wildcard characters ('*' or '?').
141VectorIsObsoleteThe java.util.Vector class is effectively obsolete. Use the Java Collections Framework classes instead, including ArrayList or Collections.synchronizedList(). See the JDK javadoc.
142WhileStatementBracesUse braces for while statements, even for a single statement.