# Checks for Coding problems |

## ArrayTrailingComma #### Description 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. #### Examples To configure the check:
    <module name="ArrayTrailingComma"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## AvoidInlineConditionals #### Description 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. #### Examples To configure the check:
    <module name="AvoidInlineConditionals"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## CovariantEquals #### Description 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. #### Example To configure the check:
    <module name="CovariantEquals"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## DoubleCheckedLocking #### Description The "double-checked locking" idiom (DCL) tries to avoid the runtime cost of synchronization. An example that uses the DCL idiom is this:
    public class MySingleton
    {
        private static theInstance = null;

        private MySingleton() {}

        public MySingleton getInstance() {
            if ( theInstance == null ) { // synchronize only if necessary
                synchronized( MySingleton.class ) {
                    if ( theInstance == null ) {
                        theInstance = new MySingleton();
                    }
                }
            }
        }
    }
The problem with the DCL idiom in Java is that it just does not work correctly. Using it introduces bugs that are extremely hard to track down and reproduce. The "Double-Checked Locking is Broken" Declaration has an in depth explanation of the exact problem which has to do with the semantics of the Java memory model. The DoubleCheckedLocking check will find source code where a test is wrapped in a synchronized block that is wrapped in the same test, like in the example above. #### Examples To configure the check:
    <module name="DoubleCheckedLocking"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## EmptyStatement #### Description Detects empty statements (standalone ;). #### Examples To configure the check:
    <module name="EmptyStatement"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## EqualsHashCode #### Description 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. #### Example To configure the check:
    <module name="EqualsHashCode"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## FinalLocalVariable #### Description 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. #### Properties
name | description | type | default value
--- | --- | --- | ---
tokens | tokens to check | subset of tokens PARAMETER_DEF, VARIABLE_DEF | VARIABLE_DEF
#### Examples 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"/>
        <property name="tokens" value="PARAMETER_DEF"/>
    </module>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## HiddenField #### Description Checks that a local variable or a parameter does not shadow a field that is defined in the same class. #### Properties
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
#### Examples 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>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## IllegalInstantiation #### Description 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. #### Notes There is a limitation that it is currently not possible to specify array classes.
name | description | type | default value
--- | --- | --- | ---
classes | classes that should not be instantiated | String Set | {}
#### Example To configure the check to find instantiations of java.lang.Boolean:
    <module name="IllegalInstantiation">
        <property name="classes" value="java.lang.Boolean"/>
    </module>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## IllegalToken #### Description 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
#### Example To configure the check to find token LITERAL_NATIVE:
    <module name="IllegalToken">
        <property name="tokens" value="LITERAL_NATIVE"/>
    </module>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## IllegalTokenText #### Description Checks for illegal token text.
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)
#### Examples 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>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## InnerAssignment #### Description 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. #### Properties
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
#### Examples 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>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## MagicNumber #### Description 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. #### Properties
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
#### Examples 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>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## MissingSwitchDefault #### Description 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. #### Examples To configure the check:
    <module name="MissingSwitchDefault"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## RedundantThrows #### Description Checks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception. #### Properties
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
#### Examples 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>
#### Note The classpath should be configured to locate the class information. The classpath configuration is dependent on the mechanism used to invoke Checkstyle. #### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## SimplifyBooleanExpression #### Description 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. #### Example To configure the check:
    <module name="SimplifyBooleanExpression"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## SimplifyBooleanReturn #### Description 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. #### Example To configure the check:
    <module name="SimplifyBooleanReturn"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## StringLiteralEquality #### Description 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))`. #### Example To configure the check:
    <module name="StringLiteralEquality"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## NestedIfDepth #### Description Restricts nested if-else blocks to a specified depth (default = 1). #### Properties
name | description | type | default value
--- | --- | --- | ---
max | allowed nesting depth | Integer | 1
#### Example 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>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## NestedTryDepth #### Description Restricts nested try blocks to a specified depth (default = 1). #### Properties
name | description | type | default value
--- | --- | --- | ---
max | allowed nesting depth | Integer | 1
#### Example 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>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## SuperClone #### Description Checks that an overriding clone() method invokes super.clone(). Reference: Object.clone(). #### Examples To configure the check:
    <module name="SuperClone"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## SuperFinalize #### Description Checks that an overriding finalize() method invokes super.finalize(). Reference: Cleaning Up Unused Objects. #### Examples To configure the check:
    <module name="SuperFinalize"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## IllegalCatch #### Description 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. #### Properties
name | description | type | default value
--- | --- | --- | ---
illegalClassNames | exception class names to reject | list of strings | "java.lang.Exception, java.lang.Throwable, java.lang.RuntimeException"
#### Examples To configure the check:
    <module name="IllegalCatch"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## PackageDeclaration #### Description Ensure a class is has a package declaration. Rationale: Classes that live in the null package cannot be imported. Many novice developers are not aware of this. #### Examples To configure the check:
    <module name="PackageDeclaration"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## JUnitTestCase #### Description 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. #### Examples To configure the check:
    <module name="JUnitTestCase"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## ReturnCount #### Description 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. #### Properties
name | description | type | default value
--- | --- | --- | ---
max | maximum allowed number of return statments | Integer | 2
format | method names to ingone | regular expression | ^equals$ (empty)
#### Examples 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>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## IllegalType #### Description 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 themsleves. #### Properties
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"
ignoredMethodNames | methods that should not be checked | String Set | "getInitialContext, getEnvironment"
#### Examples To configure the check so that it ignore getInstance() method:
    <module name="IllegalType">
        <property name="ignoredMethodNames" value="getInstance"/>
    </module>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## DeclarationOrder #### Description According to Code Conventions for the Java Programming Language , the parts of a class or interface declaration should appear in the following order Class (static) variables. First the public class variables, then the protected, then package level (no access modifier), and then the private. Instance variables. First the public class variables, then the protected, then package level (no access modifier), and then the private. Constructors Methods #### Examples To configure the check:
    <module name="DeclarationOrder"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## ParameterAssignment #### Description 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. #### Examples To configure the check:
    <module name="ParameterAssignment"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## ExplicitInitialization #### Description 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. #### Examples To configure the check:
    <module name="ExplicitInitialization"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## DefaultComesLast #### Description 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. #### Examples To configure the check:
    <module name="DefaultComesLast"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## MissingCtor #### Description Checks that classes (except abtract one) define a ctor and don't rely on the default one. #### Examples To configure the check:
    <module name="MissingCtor"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## FallThrough #### Description Checks for fall through in switch statements Finds locations where a case contains Java code - but lacks a break, return, throw or continue statement. Note: the check works in assumption that there is no unreachable code in the case. #### Examples To configure the check:
    <module name="FallThrough"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## MultipleVariableDeclarations #### Description 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. #### Examples To configure the check:
    <module name="MultipleVariableDeclarations"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## RequireThis #### Description 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)". #### Properties
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
#### Examples 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>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker ## UnnecessaryParentheses #### Description Checks for the use of unnecessary parentheses. #### Examples To configure the check:
    <module name="UnnecessaryParentheses"/>
#### Package com.puppycrawl.tools.checkstyle.checks.coding #### Parent Module TreeWalker

Back to the Checkstyle Home Page

Copyright © 2002-2003 Oliver Burn. All rights Reserved.