Checks for Coding problems |
![]() |
|
ArrayTrailingCommaDescriptionChecks 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. ExamplesTo configure the check: <module name="ArrayTrailingComma"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleAvoidInlineConditionalsDescriptionDetects 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. ExamplesTo configure the check: <module name="AvoidInlineConditionals"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleCovariantEqualsDescriptionChecks 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. ExampleTo configure the check: <module name="CovariantEquals"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleDoubleCheckedLockingDescriptionThe "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. ExamplesTo configure the check: <module name="DoubleCheckedLocking"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleEmptyStatementDescriptionDetects empty statements (standalone ;). ExamplesTo configure the check: <module name="EmptyStatement"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleEqualsHashCodeDescriptionChecks 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. ExampleTo configure the check: <module name="EqualsHashCode"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleFinalLocalVariableDescriptionChecks 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
ExamplesTo 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> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleHiddenFieldDescriptionChecks that a local variable or a parameter does not shadow a field that is defined in the same class. Properties
ExamplesTo 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> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleIllegalInstantiationDescriptionChecks 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. NotesThere is a limitation that it is currently not possible to specify array classes.
ExampleTo configure the check to find instantiations of java.lang.Boolean: <module name="IllegalInstantiation"> <property name="classes" value="java.lang.Boolean"/> </module> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleIllegalTokenDescriptionChecks 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.
ExampleTo configure the check to find token LITERAL_NATIVE: <module name="IllegalToken"> <property name="tokens" value="LITERAL_NATIVE"/> </module> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleIllegalTokenTextDescriptionChecks for illegal token text.
ExamplesTo 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> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleInnerAssignmentDescriptionChecks 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
ExamplesTo 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> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleMagicNumberDescriptionChecks 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
ExamplesTo 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> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleMissingSwitchDefaultDescriptionChecks 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. ExamplesTo configure the check: <module name="MissingSwitchDefault"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleRedundantThrowsDescriptionChecks for redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception. Properties
ExamplesTo 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> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleSimplifyBooleanExpressionDescriptionChecks 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. ExampleTo configure the check: <module name="SimplifyBooleanExpression"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleSimplifyBooleanReturnDescriptionChecks 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. ExampleTo configure the check: <module name="SimplifyBooleanReturn"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleStringLiteralEqualityDescription
Checks that string literals are not used with
Rationale: Novice Java programmers often use code like
ExampleTo configure the check: <module name="StringLiteralEquality"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleNestedIfDepthDescriptionRestricts nested if-else blocks to a specified depth (default = 1). Properties
ExampleTo configure the check: <module name="NestedIfDepth"/> To configure the check to allow nesting depth 3: <module name="NestedIfDepth"> <property name="max" value="3"/> </module> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleNestedTryDepthDescriptionRestricts nested if-else blocks to a specified depth (default = 1). Properties
ExampleTo configure the check: <module name="NestedTryDepth"/> To configure the check to allow nesting depth 3: <module name="NestedTryDepth"> <property name="max" value="3"/> </module> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleSuperCloneDescriptionChecks that an overriding clone() method invokes super.clone(). Reference: Object.clone(). ExamplesTo configure the check: <module name="SuperClone"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleSuperFinalizeDescriptionChecks that an overriding finalize() method invokes super.finalize(). Reference: Cleaning Up Unused Objects. ExamplesTo configure the check: <module name="SuperFinalize"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleIllegalCatchDescriptionCatching 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
ExamplesTo configure the check: <module name="IllegalCatch"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModulePackageDeclarationDescriptionEnsure 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. ExamplesTo configure the check: <module name="PackageDeclaration"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleJUnitTestCaseDescription
Ensures that the setUp(), tearDown()methods are named correctly,
have no arguments, return void and are either public or protected. Rationale: often times developers will misname one or more of these methods and not realise that the method is not being called. ExamplesTo configure the check: <module name="JUnitTestCase"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleReturnCountDescriptionRestrict the number of return statements. Default = 2. Rationale: Too many return points can be indication that code is attempting to do too much or may be difficult to understand. Properties
ExamplesTo configure the check so that it doesn't allow more than three return statements per method: <module name="ReturnCount"> <property name="max" value="3"/> </module> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleIllegalTypeDescriptionChecks 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
ExamplesTo configure the check so that it ignore getInstance() method: <module name="IllegalType"> <property name="ignoredMethodNames" value="getInstance"/> </module> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleDeclarationOrderDescriptionAccording to Code Conventions for the Java Programming Language , the parts of a class or interface declaration should appear in the following order ExamplesTo configure the check: <module name="DeclarationOrder"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleParameterAssignmentDescriptionDisallow 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. ExamplesTo configure the check: <module name="ParameterAssignment"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent ModuleExplicitInitializationDescriptionChecks 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. ExamplesTo configure the check: <module name="ExplicitInitialization"/> Packagecom.puppycrawl.tools.checkstyle.checks.coding Parent Module |
Copyright © 2002-2003 Oliver Burn. All rights Reserved.