The CodeNarc Team is proud to announce the release of version 0.14. CodeNarc is a static analysis tool for Groovy source code. Version 0.14 adds 35 new rules (bringing the total to 241 rules). Try it out on the CodeNarc web console, running on Google App Engine.
Groovy 1.8 Support - CodeNarc continues to be built with Groovy 1.7, but should be able to be run with a Groovy 1.8 Runtime.
New and Updated Rules
·ExplicitLinkedHashMapInstantiation rule (basic) - This 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.
·DuplicateMapKey rule (basic) - A map literal is created with duplicated key. The map entry will be overwritten.
·DuplicateSetValue rule (basic) - A Set literal is created with duplicate constant value. A set cannot contain two elements with the same value.
·EqualsOverloaded rule (basic) - The 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.
·ForLoopShouldBeWhileLoop (basic) - A for-loop without an init and an update statement can be simplified to a while loop.
·NonFinalSubclassOfSensitiveInterface rule (security) - The 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.
·ImportFromSunPackages rule (imports) - Avoid importing anything from the 'sun.*' packages. These packages are not portable and are likely to change.
·UnnecessaryFinalOnPrivateMethod rule (unnecessary) - A private method is marked final. Private methods cannot be overridden, so marking it final is unnecessary.
·InsecureRandom rule (security) - Reports 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.
·DirectConnectionManagement rule (jdbc) - The 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.
·ComparisonWithSelf (basic) - Checks for using a comparison operator or equals() or compareTo() to compare a variable to itself, e.g.: x == x, x != x, x <=> x, x < x, x > x, x <= x, x >= x, x.equals(x), or x.compareTo(x), where x is a variable.
·ComparisonOfTwoConstants (basic) - Checks for using a comparison operator or equals() or compareTo() to compare two constants to each other or two literals that contain only constant values.
·FileCreateTempFile rule (security) - The 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.
·SystemExit rule (security) - Web 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.
·ObjectFinalize rule (security) - The finalize() method should only be called by the JVM after the object has been garbage collected.
·JavaIoPackageAccess rule (security) - This rule reports violations of the Enterprise JavaBeans specification by using the java.io package to access files or the file system.
·UnsafeArrayDeclaration rule (security) - Triggers 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.
·PublicFinalizeMethod rule (security) - Creates a violation when the program violates secure coding principles by declaring a finalize() method public.
·NonFinalPublicField rule (security) - Finds code that violates secure coding principles for mobile code by declaring a member variable public but not final.
·UnnecessaryElseStatement rule (unnecessary) - When 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.
·StaticConnection rule (concurrency) - Creates 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.
·UnnecessaryPackageReference (unnecessary) - Checks for explicit package reference for classes that Groovy imports by default, such as java.lang.String, java.util.Map and groovy.lang.Closure.
·AbstractClassWithPublicConstructor (design) - Checks for abstract classes that define a public constructor, which is useless and confusing.
·StaticSimpleDateFormatField (concurrency) - Checks for static SimpleDateFormat fields. SimpleDateFormat objects are not threadsafe, and should not be shared across threads.
·IllegalPackageReference (generic) - Checks for reference to any of the packages configured in packageNames.
·SpockIgnoreRestUsed rule (junit) - If Spock's @IgnoreRest appears on any method, then 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.
·SwallowThreadDeath rule (exceptions) - Detects code that catches java.lang.ThreadDeath without rethrowing it
·MisorderedStaticImports rule (imports) - Static imports should never be declared after nonstatic imports.
·ConfusingMethodName (naming) - Existing rule updated to analyze fields and field names as well as just methods.
·PublicInstanceField rule (design) - Using public fields is considered to be a bad design. Use properties instead.
·UnnecessaryNullCheck (unnecessary) - Updated rule to flag null and not-null checks against the this reference. The this reference can never be null.
·ClassForName rule (basic) - Using 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.
·StatelessSingleton rule (design) - Rule finds occurrences of the Singleton pattern where the object has no state (mutable or otherwise). There is no point in creating a stateless Singleton, just make a new instance with the new keyword instead.
·InconsistentPropertySynchronization rule (concurrency) - The rule is a little smarter now and flags code that defines a synchronized getter without any setter and vice versa. Those methods will be generated in unsynchronized from by the Groovy compiler later.
·ClosureAsLastMethodParameter rule (basic) - If a method is called and the last parameter is an inline closure then it can be declared outside of the method call brackets.
·SerialPersistentFields rule (serialization) - To use a Serializable object's serialPersistentFields correctly, it must be declared private, static, and final.
·UnnecessaryParenthesesForMethodCallWithClosure rule (unnecessary) - If a method is called and the only parameter to that method is an inline closure then the brackets of the method call can be omitted.
·#3290486 - AbstractClassWithoutAbstractMethod no longer flags marker interfaces as abstract classes that do not define a method.
·#3202691 - ClassNameRule rule is changed to handle $ in the class name, which is in Inner and Nested classes by default.
·#3206167 - VariableNameRule now has a violation message that states the name of the variable and the regex it did not match.
·#3206667 - FieldName, VariableName, MethodName, ParameterName, UnusedVariable, PropertyName, and UnusedPrivateField violations message now contains the class name of the enclosing class. This helps you configure an exclude.
·#3206258 - LoggerForDifferentClass rule now accepts MyClass.name as a valid name for the logger.
·#3206238 - The DuplicateNumberLiteral rule now allows you to ignore literals in the 1.2d, 1.2f, and 1.2G format.
·#3207628 - The UnusedPrivateMethodParameter rule now allows you to ignore parameters by name. By default, parameters named 'ignore' and 'ignored' do not trigger a violation. You can configure this with the 'ignoreRegex' property on the rule.
·#3205696 - The ConsecutiveStringConcatenation rule no longer suggesting that you join numbers together, it only suggests joining strings together.
·#3206150 - Fixed UnusedGroovyImport rule so that imports with aliases are ignored and do not cause violations.
·#3207605 - Fixed UnusedPrivateMethod rule to recognize static method references.
·#3207607 - Fixed UnusedPrivateMethod rule to recognize access of privately defined getters and setters as properties.
·#3205697 - Fixed bug where the source line displayed for annotated nodes was sometimes showing just the annotation and not the node.
·#3288895 - Expand default test file regex pattern to include *TestCase
·#3291474 - Enhance StaticDateFormatFieldRule to also check for static fields initialized to a DateFormat, e.g. static final DATE_FORMAT = DateFormat.getDateInstance(DateFormat.LONG)
·#3291559 - Enhance StaticCalendarFieldRule to also check for untyped static fields that are initialized to a Calendar, e.g. static final CALENDAR = Calendar.getInstance()
·#3305896 - Fix LoggerForDifferentClass: The rule now correctly handles inner classes (that are not static)
·#3305019 - Updated the EmptyCatchBlockRule so that exceptions named ignore or ignored will not trigger errors. The name is configurable.
-Fixed the Explicit[Collection]Instantiation rules so that the error messages are more descriptive.
-Fixed the InconsistentPropertySynchronization rule so that it recognizes the new @Synchronized annotation.
·#3308930 - LoggerWithWrongModifiersRule now contains a parameter 'allowProtectedLogger' so that loggers can also be instantiated as 'protected final LOG = Logger.getLogger(this.class)'. Also, it has a 'allowNonStatic' logger property, that allows you to create a non static logger.
·#3308930 - LoggerForDifferentClassRule now contains a parameter 'allowDerivedClasses'. When set, a logger may be created about this.getClass().
·#3309748 - FieldName:Do not treat non-static final fields as constants
·#3310413 - Fix UnnecessaryPublicModifier does not catch public on constructors.
·#3310521 - For all ExplicitCallToXxxMethod rules: Ignore calls to super.Xxx(). Patch from René Scheibe
·#3313550 - Some HTML violation descriptions in the properties files were not well-formed HTML. This has been fixed.
·#3205688 - Fixed false positives in UseAssertEqualsInsteadOfAssertTrue when using the JUnit assertFalse method.
Breaking Changes ****
·Moved the following rules out of the "basic" ruleset into the new "serialization" ruleset:
·[Developer] Moved import-specific helper methods out of AbstractRule into ImportUtil.
·[Developer] The ExplicitTypeInstantiationAstVisitor is now an abstract class that requires you to specify a custom violation message. This should affect no one, but it is a backwards breaking change.
Thank you to Victor Savkin for sending in a patch with the ForLoopShouldBeWhileLoop, UnnecessaryElse, StatelessSingleton, PublicInstanceField, and EmptyCatchBlock rules.
Thank you to Jan Ahrens and Stefan Armbruster for the SpockIgnoreRestUsed rule.
Thank you to Rob Fletcher and Klaus Baumecker for the SwallowThreadDeath rule.
Thank you to Erik Pragt for the MisorderedStaticImports rule.
Thank you to Marcin Erdmann for the MisorderedStaticImports, ClosureAsLastMethodParameterInBracketsRule, and UnnecessaryBracketsForMethodWithClosureCall rules.
Thank you to Hubert 'Mr. Haki' Klein Ikkink for updating the ConfusingMethodName rule.
Thank you to René Scheibe for the ExplicitLinkedHashMapInstantiation rule and UnnecessaryGroovyImportRule and ExplicitCallToXxxMethod patches.