Checks that array initialization contains a trailing comma.
int[] a = new int[] { 1, 2, 3, };
The check allows to not add a comma if both left and right curlys are on the same line.
return new int[] { 0 };
Rationale: Putting this comma in makes it easier to change the order of the elements or add new elements on the end.
Detects inline conditionals. An example inline conditional is this:
String a = getParameter("a"); String b = (a==null || a.length<1) ? null : a.substring(1);
Rationale: Some developers find inline conditionals hard to read, so their company's coding standards forbids them.
Checks that classes that define a covariant equals() method also override method equals(java.lang.Object). Inspired by findbugs.
Rationale: Mistakenly defining a covariant equals() method without overriding method equals(java.lang.Object) can produce unexpected runtime behaviour.
Checks that any combination of String literals with optional assignment is on the left side of an equals() comparison. The check also processes String.equalsIgnoreCase() invocations (which can be suppressed).
Rationale: Calling the equals() method on String literals will avoid a potential NullPointerException. Also, it is pretty common to see null check right before equals comparisons which is not necessary in the below example.
For example:
String nullString = null; nullString.equals("My_Sweet_String");
should be refactored to:
String nullString = null; "My_Sweet_String".equals(nullString);
Limitations: If the equals method is overridden or a covariant equals method is defined and the implementation is incorrect (where s.equals(t) does not return the same result as t.equals(s)) then rearranging the called on object and parameter may have unexpected results
Java's Autoboxing feature has an affect on how this check is implemented. Pre Java 5 all IDENT + IDENT object concatenations would not cause a NullPointerException even if null. Those situations could have been included in this check. They would simply act as if they surrounded by String.valueof() which would concatenate the String null.
The following example will cause a NullPointerException as a result of what autoboxing does.
Integer i = null, j = null; String number = "5" number.equals(i + j);
Since, it is difficult to determine what kind of Object is being concatenated all ident concatenation is considered unsafe.
name | description | type | default value |
---|---|---|---|
ignoreEqualsIgnoreCase | whether to ignore String.equalsIgnoreCase() invocations | boolean | false |
Checks that classes that override equals() also override hashCode().
Rationale: The contract of equals() and hashCode() requires that equal objects have the same hashCode. Hence, whenever you override equals() you must override hashCode() to ensure that your class can be used in collections that are hash based.
Checks that local variables that never have their values changed are declared final. The check can be configured to also check that unchanged parameters are declared final.
When configured to check parameters, the check ignores parameters of interface methods and abstract methods.
name | description | type | default value |
---|---|---|---|
tokens | tokens to check | subset of tokens PARAMETER_DEF, VARIABLE_DEF | VARIABLE_DEF |
To configure the check:
<module name="FinalLocalVariable"/>
To configure the check so that it checks local variables and parameters:
<module name="FinalLocalVariable"> <property name="tokens" value="VARIABLE_DEF,PARAMETER_DEF"/> </module>
Checks that a local variable or a parameter does not shadow a field that is defined in the same class.
name | description | type | default value |
---|---|---|---|
tokens | tokens to check | subset of tokens PARAMETER_DEF, VARIABLE_DEF | PARAMETER_DEF, VARIABLE_DEF |
ignoreFormat | pattern for names to ignore | regular expression | (not applied) |
ignoreConstructorParameter | Controls whether to ignore constructor parameters. | Boolean | false |
ignoreSetter | Controls whether to ignore the parameter of a property setter method, where the property setter method for field "xyz" has name "setXyz", one parameter named "xyz", and return type void. | Boolean | false |
ignoreAbstractMethods | Controls whether to ignore parameters of abstract methods. | Boolean | false |
To configure the check:
<module name="HiddenField"/>
To configure the check so that it checks local variables but not parameters:
<module name="HiddenField"> <property name="tokens" value="VARIABLE_DEF"/> </module>
To configure the check so that it ignores the name "rcsid":
<module name="HiddenField"> <property name="ignoreFormat" value="^rcsid$"/> </module>
To configure the check so that it ignores constructor parameters:
<module name="HiddenField"> <property name="ignoreConstructorParameter" value="true"/> </module>
To configure the check so that it ignores the parameter of setter methods:
<module name="HiddenField"> <property name="ignoreSetter" value="true"/> </module>
Checks for illegal instantiations where a factory method is preferred.
Rationale: Depending on the project, for some classes it might be preferable to create instances through factory methods rather than calling the constructor.
A simple example is the java.lang.Boolean class. In order to save memory and CPU cycles, it is preferable to use the predefined constants TRUE and FALSE. Constructor invocations should be replaced by calls to Boolean.valueOf().
Some extremely performance sensitive projects may require the use of factory methods for other classes as well, to enforce the usage of number caches or object pools.
name | description | type | default value |
---|---|---|---|
classes | classes that should not be instantiated | String Set | {} |
To configure the check to find instantiations of java.lang.Boolean:
<module name="IllegalInstantiation"> <property name="classes" value="java.lang.Boolean"/> </module>
Checks for illegal tokens.
Rational: Certain language features often lead to hard to maintain code or are non-obvious to novice developers. Other features may be discouraged in certain frameworks, such as not having native methods in EJB components.
name | description | type | default value |
---|---|---|---|
tokens | tokens to check | subset of TokenTypes, | LITERAL_SWITCH, POST_INC, POST_DEC |
To configure the check to find token LITERAL_NATIVE:
<module name="IllegalToken"> <property name="tokens" value="LITERAL_NATIVE"/> </module>
name | description | type | default value |
---|---|---|---|
tokens | tokens to check | subset of TokenTypes | empty |
format | illegal pattern | regular expression | ^$ (empty) |
ignoreCase | Controls whether to ignore case when matching. | Boolean | false |
message | Message which is used to notify about violations; if empty then the default message is used. | String | ""(empty) |
To configure the check to forbid String literals containing "a href":
<module name="IllegalTokenText"> <property name="tokens" value="STRING_LITERAL"/> <property name="format" value="a href"/> </module>
To configure the check to forbid leading zeros in an integer literal, other than zero and a hex literal:
<module name="IllegalTokenText"> <property name="tokens" value="NUM_INT,NUM_LONG"/> <property name="format" value="^0[^lx]"/> <property name="ignoreCase" value="true"/> </module>
Checks for assignments in subexpressions, such as in String s = Integer.toString(i = 2);.
Rationale: With the exception of for iterators, all assignments should occur in their own toplevel statement to increase readability. With inner assignments like the above it is difficult to see all places where a variable is set.
name | description | type | default value |
---|---|---|---|
tokens | assignments to check | subset of tokens ASSIGN, BAND_ASSIGN, BOR_ASSIGN, BSR_ASSIGN, BXOR_ASSIGN, DIV_ASSIGN, MINUS_ASSIGN, MOD_ASSIGN, PLUS_ASSIGN, SL_ASSIGN, SR_ASSIGN, STAR_ASSIGN | all tokens |
To configure the check:
<module name="InnerAssignment"/>
To configure the check for only =, +=, and -= operators:
<module name="InnerAssignment"> <property name="tokens" value="ASSIGN,PLUS_ASSIGN,MINUS_ASSIGN"/> </module>
Checks that there are no "magic numbers", where a magic number is a numeric literal that is not defined as a constant. By default, -1, 0, 1, and 2 are not considered to be magic numbers.
name | description | type | default value |
---|---|---|---|
tokens | tokens to check | subset of tokens NUM_DOUBLE, NUM_FLOAT, NUM_INT, NUM_LONG | all tokens |
ignoreNumbers | non-magic numbers | list of numbers | -1, 0, 1, 2 |
ignoreHashCodeMethod | ignore magic numbers in hashCode methods | boolean | false |
ignoreAnnotation | ignore magic numbers in annotation declarations. | boolean | false |
To configure the check:
<module name="MagicNumber"/>
To configure the check so that it checks floating-point numbers that are neither 0, 0.5, nor 1:
<module name="MagicNumber"> <property name="tokens" value="NUM_DOUBLE, NUM_FLOAT"/> <property name="ignoreNumbers" value="0, 0.5, 1"/> </module>
Checks that switch statement has "default" clause.
Rationale: It's usually a good idea to introduce a default case in every switch statement. Even if the developer is sure that all currently possible cases are covered, this should be expressed in the default branch, e.g. by using an assertion. This way the code is protected aginst later changes, e.g. introduction of new types in an enumeration type.
Check for ensuring that for loop control variables are not modified inside the for block. An example is:
for (int i = 0; i < 1; i++) { i++; }
Rationale: If the control variable is modified inside the loop body, the program flow becomes more difficult to follow. An option is to replace the for loop with a while loop.
Checks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception.
name | description | type | default value |
---|---|---|---|
allowUnchecked | whether unchecked exceptions in throws are allowed or not | boolean | false |
allowSubclasses | whether subclass of another declared exception is allowed in throws clause | boolean | false |
logLoadErrors | This check may need to load exception classes mentioned in the @throws tag to check whether they are RuntimeExceptions. If loading the class fails, this property allows to control checkstyle's error handling. If set to false a classpath configuration problem is assumed and the TreeWalker stops operating on the class completely. If set to true (the default), checkstyle assumes a typo or refactoring problem in the javadoc and logs the problem in the normal checkstyle report (potentially masking a configuration error). | boolean | true |
suppressLoadErrors | When logLoadErrors is set to true, the TreeWalker completely processes a class and displays any problems with loading exceptions as checkstyle violations. When this property is set to true, the violations generated when logLoadErrors is set true are suppressed from being reported as violations in the checkstyle report. | boolean | false |
To configure the default check:
<module name="RedundantThrows"/>
To configure the check to allow unchecked exception in throws clause
<module name="RedundantThrows"> <property name="allowUnchecked" value="true"/> </module>
The classpath should be configured to locate the class information. The classpath configuration is dependent on the mechanism used to invoke Checkstyle.
Checks for overly complicated boolean expressions. Currently finds code like if (b == true), b || true, !false, etc.
Rationale: Complex boolean logic makes code hard to understand and maintain.
Checks for overly complicated boolean return statements. For example the following code
if (valid()) return false; else return true;
could be written as
return !valid();
The Idea for this Check has been shamelessly stolen from the equivalent PMD rule.
Checks that string literals are not used with == or !=.
Rationale: Novice Java programmers often use code like:
if (x == "something")
when they mean
if ("something".equals(x))
name | description | type | default value |
---|---|---|---|
max | allowed nesting depth | Integer | 1 |
To configure the check:
<module name="NestedForDepth"/>
To configure the check to allow nesting depth 3:
<module name="NestedForDepth"> <property name="max" value="3"/> </module>
name | description | type | default value |
---|---|---|---|
max | allowed nesting depth | Integer | 1 |
To configure the check:
<module name="NestedIfDepth"/>
To configure the check to allow nesting depth 3:
<module name="NestedIfDepth"> <property name="max" value="3"/> </module>
name | description | type | default value |
---|---|---|---|
max | allowed nesting depth | Integer | 1 |
To configure the check:
<module name="NestedTryDepth"/>
To configure the check to allow nesting depth 3:
<module name="NestedTryDepth"> <property name="max" value="3"/> </module>
Checks that the clone method is not overridden from the Object class.
Rationale: The clone method relies on strange/hard to follow rules that do not work it all situations. Consequently, it is difficult to override correctly. Below are some of the rules/reasons why the clone method should be avoided.
Two alternatives to the clone method, in some cases, is a copy constructor or a static factory method to return copies of an object. Both of these approaches are simpler and do not conflict with final fields. The do not force the calling client to handle a CloneNotSuportException. They also are typed therefore no casting is necessary. Finally, they are more flexible since they can take interface types rather than concrete classes.
Sometimes a copy constructor or static factory is not an acceptable alternative to the clone method. The example below highlights the limitation of a copy constructor (or static factory). Assume Square is a subclass for Shape.
Shape s1 = new Square(); System.out.println(s1 instanceof Square); //true
...assume at this point the code knows nothing of s1 being a Square that's the beauty of polymorphism but the code wants to copy the Square which is declared as a Shape, its super type...
Shape s2 = new Shape(s1); //using the copy constructor System.out.println(s2 instanceof Square); //false
The working solution (without knowing about all subclasses and doing many casts) is to do the following (assuming correct clone implementation).
Shape s2 = s1.clone(); System.out.println(s2 instanceof Square); //true
Just keep in mind if this type of polymorphic cloning is required then a properly implemented clone method may be the best choice.
Much of this information was taken from Effective Java: Programming Language Guide First Edition by Joshua Bloch pages 45-52. Give Bloch credit for writing an excellent book.
This check is almost exactly the same as the {@link NoFinalizerCheck}
Checks that an overriding clone() method invokes super.clone().
Reference: Object.clone().
Checks that an overriding finalize() method invokes super.finalize().
Reference: Cleaning Up Unused Objects.
Catching java.lang.Exception, java.lang.Error or java.lang.RuntimeException is almost never acceptable.
Rationale: Junior developers often simply catch Exception in an attempt to handle multiple exception classes. This unfortunately leads to code that inadvertantly catchs NPE, OutOfMemoryErrors, etc.
name | description | type | default value |
---|---|---|---|
illegalClassNames | exception class names to reject | list of strings | "java.lang.Exception, java.lang.Throwable, java.lang.RuntimeException" |
This check can be used to ensure that types are not declared to be thrown. Declaring to throw java.lang.Error or java.lang.RuntimeException is almost never acceptable.
name | description | type | default value |
---|---|---|---|
illegalClassNames | throw class names to reject | list of strings | "java.lang.Throwable, java.lang.Error, java.lang.RuntimeException" |
ignoredMethodNames | names of methods to ignore | list of strings | finalize |
Ensure a class is has a package declaration, and (optionally) whether the package name matches the directory name for the source file.
Rationale: Classes that live in the null package cannot be imported. Many novice developers are not aware of this.
name | description | type | default value |
---|---|---|---|
ignoreDirectoryName | whether to ignore checking that the package declaration matches the source directory name | boolean | false |
Ensures that the setUp(), tearDown()methods are named correctly, have no arguments, return void and are either public or protected.
Also ensures that suite() is named correctly, have no arguments, return junit.framewotk.Test, public and static.
Rationale: often times developers will misname one or more of these methods and not realise that the method is not being called.
Restricts the number of return statements. Default = 2. Ignores specified methods (equals() by default).
Rationale: Too many return points can be indication that code is attempting to do too much or may be difficult to understand.
name | description | type | default value |
---|---|---|---|
max | maximum allowed number of return statments | Integer | 2 |
format | method names to ingone | regular expression | ^equals$ (empty) |
To configure the check so that it doesn't allow more than three return statements per method (equals() method ignored):
<module name="ReturnCount"> <property name="max" value="3"/> </module>
To configure the check so that it doesn't allow more than three return statements per method for all methods:
<module name="ReturnCount"> <property name="max" value="3"/> <property name="format" value="^$"/> </module>
Checks that particular class are never used as types in variable declarations, return values or parameters. Includes a pattern check that by default disallows abstract classes.
Rationale: Helps reduce coupling on concrete classes. In addition abstract classes should be thought of a convenience base class implementations of interfaces and as such are not types themselves.
name | description | type | default value |
---|---|---|---|
tokens | tokens to check | subset of tokens PARAMETER_DEF, VARIABLE_DEF METHOD_DEF | PARAMETER_DEF, VARIABLE_DEF METHOD_DEF |
illegalClassNames | classes that should not be used as types in variable declarations, return values or parameters. | String Set | "java.util.GregorianCalendar, java.util.Hashtable, java.util.HashSet, java.util.HashMap, java.util.ArrayList, java.util.LinkedList, java.util.LinkedHashMap, java.util.LinkedHashSet, java.util.TreeSet, java.util.TreeMap, java.util.Vector" |
legalAbstractClassNames | abstract classes that may be used as types. | String Set | |
ignoredMethodNames | methods that should not be checked | String Set | "getInitialContext, getEnvironment" |
format | pattern for illegal class name | regular expression | ^(.*[\\.])?Abstract.*$ |
To configure the check so that it ignore getInstance() method:
<module name="IllegalType"> <property name="ignoredMethodNames" value="getInstance"/> </module>
According to Code Conventions for the Java Programming Language , the parts of a class or interface declaration should appear in the following order:
name | description | type | default value |
---|---|---|---|
ignoreConstructors | whether to ignore constructors | Boolean | false |
ignoreMethods | whether to ignore methods | Boolean | false |
ignoreModifiers | whether to ignore modifiers | Boolean | false |
Disallow assignment of parameters.
Rationale: Parameter assignment is often considered poor programming practice. Forcing developers to declare parameters as final is often onerous. Having a check ensure that parameters are never assigned would give the best of both worlds.
Checks if any class or object member explicitly initialized to default for its type value (null for object references, zero for numeric types and char and false for boolean.
Rationale: each instance variable gets initialized twice, to the same value. Java initializes each instance variable to its default value (0 or null) before performing any initialization specified in the code. So in this case, x gets initialized to 0 twice, and bar gets initialized to null twice. So there is a minor inefficiency. This style of coding is a hold-over from C/C++ style coding, and it shows that the developer isn't really confident that Java really initializes instance variables to default values.
Check that the default is after all the cases in a switch statement.
Rationale: Java allows default anywhere within the switch statement. But it is more readable if it comes after the last case.
Checks that classes (except abtract one) define a ctor and don't rely on the default one.
Checks for fall through in switch statements Finds locations where a case contains Java code - but lacks a break, return, throw or continue statement.
The check honores special comments to supress the warning. By default the text "fallthru", "fall through", "fallthrough", "falls through" and "fallsthrough" are recognized (case sensitive). The comment containing this words must be a one-liner and must be on the last none-empty line before the case triggering the warning or on the same line before the case (urgly, but possible).
switch (i){ case 0: i++; // fall through case 1: i++; // falls through case 2: { i++; } // fallthrough case 3: i++; /* fallthru */case 4: i++ break; }
Note: the check works in assumption that there is no unreachable code in the case.
name | description | type | default value |
---|---|---|---|
checkLastCaseGroup | Whether we need to check last case group or not. | Boolean | false |
reliefPattern | Regulare expression to match the relief comment that supresses the warning about a fall through. | regular expression | fallthru|falls? ?through |
To configure the check:
<module name="FallThrough"/>
or
<module name="FallThrough"> <property name="reliefPattern" value="continue in next case"/> <module name="FallThrough"/>
Checks for multiple occurrences of the same string literal within a single file.
Rationale: Code duplication makes maintenance more difficult, so it can be better to replace the multiple occurrences with a constant.
name | description | type | default value |
---|---|---|---|
allowedDuplicates | The maximum number of occurences to allow without generating a warning | Integer | 1 |
ignoreStringsRegexp | regexp pattern for ignored strings (with quotation marks) | regular expression | ^""$ (ignore empty strings) |
ignoreOccurrenceContext | Token type names where duplicate strings are ignored even if they don't match ignoredStringsRegexp. This allows you to exclude syntactical contexts like Annotations or static initializers from the check. | list of token type names | ANNOTATION (ignore strings inside the context of an annotation) |
To configure the check:
<module name="MultipleStringLiterals"/>
To configure the check so that it allows two occurrences of each string:
<module name="MultipleStringLiterals"> <property name="allowedDuplicates" value="2"/> </module>
To configure the check so that it ignores ", " and empty strings:
<module name="MultipleStringLiterals"> <property name="ignoreStringsRegexp" value='^(("")|(", "))$'/> </module>
To configure the check so that it flags duplicate strings in all syntactical contexts, even in annotations like @SuppressWarnings("unchecked"):
<module name="MultipleStringLiterals"> <property name="ignoreOccurrenceContext" value=""/> </module>
Checks that each variable declaration is in its own statement and on its own line.
Rationale: the SUN Code conventions chapter 6.1 recommends that declarations should be one per line/statement.
Checks that code doesn't rely on the "this." default, i.e. references to instance variables and methods of the present object are explicitly of the form "this.varName" or "this.methodName(args)".
name | description | type | default value |
---|---|---|---|
checkFields | whether we should check fields usage or not | boolean | true |
checkMethods | whether we should check methods usage or not | boolean | true |
To configure the default check:
<module name="RequireThis"/>
To configure to check this qualifier for fields only:
<module name="RequireThis"> <property name="checkMethods" value="false"/> </module>