NewlineAtEndOfFile

Description

Checks whether files end with a line separator.

Rationale: Any source files and text files in general should end with a line separator, especially when using source control management systems such as CVS. CVS will even print a warning when it encounters a file that doesn't end with a line separator.

Properties

name description type default value
lineSeparator type of line separator One of "system" (system default), "crlf" (Windows-style), "cr" (Mac-style), "lf" (Unix-style) and "lf_cr_crlf" (lf, cr or crlf). "system"
fileExtensions file type extension of the files to check. String Set all files

Examples

To configure the check:

<module name="NewlineAtEndOfFile"/>
        

To configure the check to always use Unix-style line separators:

<module name="NewlineAtEndOfFile">
    <property name="lineSeparator" value="lf"/>
</module>
        

To configure the check to work only on Java, XML and Python files:

<module name="NewlineAtEndOfFile">
    <property name="fileExtensions" value="java, xml, py"/>
</module>
          

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

Checker

TodoComment

Description

A check for TODO: comments. Actually it is a generic regular expression matcher on Java comments. To check for other patterns in Java comments, set the format property.

Properties

name description type default value
format Pattern to match comments against regular expression TODO:

Notes

Using TODO: comments is a great way to keep track of tasks that need to be done. Having them reported by Checkstyle makes it very hard to forget about them.

Examples

To configure the check:

<module name="TodoComment"/>
        

To configure the check for comments that contain TODO and FIXME:

<module name="TodoComment">
    <property name="format" value="(TODO)|(FIXME)"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

TreeWalker

Translation

Description

A FileSetCheck that ensures the correct translation of code by checking property files for consistency regarding their keys. Two property files describing one and the same context are consistent if they contain the same keys.

Consider the following properties file in the same directory:

#messages.properties
hello=Hello
cancel=Cancel

#messages_de.properties
hell=Hallo
ok=OK
        

The Translation check will find the typo in the German hello key, the missing ok key in the default resource file and the missing cancel key in the German resource file:

messages_de.properties: Key 'hello' missing.
messages_de.properties: Key 'cancel' missing.
messages.properties: Key 'hell' missing.
messages.properties: Key 'ok' missing.
        

Properties

name description type default value
fileExtensions file type extension to identify translation files. Setting this property is typically only required if your translation files are preprocessed and the original files do not have the extension .properties String Set properties
basenameSeparator Allows setting file names separator String _

Example

To configure the check for files with '_' name separator:

<module name="Translation"/>
        

To configure the check for files with user-set name separator:

<module name="Translation">
    <property name="basenameSeparator" value="STRING_LITERAL"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

Checker

UncommentedMain

Description

Checks for uncommented main() methods.

Rationale: A main() method is often used for debugging purposes. When debugging is finished, developers often forget to remove the method, which changes the API and increases the size of the resulting class or JAR file. With the exception of the real program entry points, all main() methods should be removed or commented out of the sources.

Properties

name description type default value
excludedClasses Pattern for qualified names of classes which are allowed to have a main method. regular expression ^$

Examples

To configure the check:

<module name="UncommentedMain"/>
        

To configure the check to allow the main method for all classes with "Main" name:

<module name="UncommentedMain">
    <property name="excludedClasses" value="\.Main$"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

TreeWalker

UpperEll

Description

Checks that long constants are defined with an upper ell. That is ' L' and not 'l'. This is in accordance with the Java Language Specification, Section 3.10.1.

The capital L looks a lot like 1.

Examples

To configure the check:

<module name="UpperEll"/>
        

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

TreeWalker

ArrayTypeStyle

Description

Checks the style of array type definitions. Some like Java style: public static void main(String[] args) and some like C style: public static void main(String args[])

Properties

name description type default value
javaStyle Controls whether to enforce Java style (true) or C style (false). Boolean true

Examples

To configure the check to enforce Java style:

<module name="ArrayTypeStyle"/>
        

To configure the check to enforce C style:

<module name="ArrayTypeStyle">
    <property name="javaStyle" value="false"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

TreeWalker

FinalParameters

Description

Check that parameters for methods, constructors, and catch blocks are final. Interface and abstract methods are not checked: the final keyword does not make sense for interface and abstract method parameters as there is no code that could modify the parameter.

Rationale: Changing the value of parameters during the execution of the method's algorithm can be confusing and should be avoided. A great way to let the Java compiler prevent this coding style is to declare parameters final.

Properties

name description type default value
tokens blocks to check subset of tokens METHOD_DEF, CTOR_DEF, LITERAL_CATCH METHOD_DEF, CTOR_DEF
ignorePrimitiveTypes ignore primitive types as parameters Boolean false

Examples

To configure the check to enforce final parameters for methods and constructors:

<module name="FinalParameters"/>
        

To configure the check to enforce final parameters only for constructors:

<module name="FinalParameters">
    <property name="tokens" value="CTOR_DEF"/>
</module>
        

To configure the check to allow ignoring primitive datatypes as parameters:

<module name="FinalParameters">
    <property name="ignorePrimitiveTypes" value="true"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

TreeWalker

DescendantToken

Description

Checks for restricted tokens beneath other tokens.

WARNING: This is a very powerful and flexible check, but, at the same time, it is low-level and very implementation-dependent because its results depend on the grammar we use to build abstract syntax trees. Thus we recommend using other checks when they provide the desired functionality. Essentially, this check just works on the level of an abstract syntax tree and knows nothing about language structures.

Properties

name description type default value
tokens token types to check subset of tokens declared in TokenTypes empty set
limitedTokens set of tokens with limited occurrences as descendants subset of tokens declared in TokenTypes empty set
minimumDepth the minimum depth for descendant counts Integer 0
maximumDepth the maximum depth for descendant counts Integer java.lang.Integer.MAX_VALUE
minimumNumber a minimum count for descendants Integer 0
maximumNumber a maximum count for descendants Integer java.lang.Integer.MAX_VALUE
sumTokenCounts whether the number of tokens found should be calculated from the sum of the individual token counts Boolean false
minimumMessage error message when the minimum count is not reached String "descendant.token.min"
maximumMessage error message when the maximum count is exceeded String "descendant.token.max"

Examples

Comparing this with null (i.e. this == null and this != null):

<module name="DescendantToken">
    <property name="tokens" value="EQUAL,NOT_EQUAL"/>
    <property name="limitedTokens" value="LITERAL_THIS,LITERAL_NULL"/>
    <property name="maximumNumber" value="1"/>
    <property name="maximumDepth" value="1"/>
    <property name="sumTokenCounts" value="true"/>
</module>
        

String literal equality check:

<module name="DescendantToken">
    <property name="tokens" value="EQUAL,NOT_EQUAL"/>
    <property name="limitedTokens" value="STRING_LITERAL"/>
    <property name="maximumNumber" value="0"/>
    <property name="maximumDepth" value="1"/>
</module>
        

Switch with no default:

<module name="DescendantToken">
    <property name="tokens" value="LITERAL_SWITCH"/>
    <property name="maximumDepth" value="2"/>
    <property name="limitedTokens" value="LITERAL_DEFAULT"/>
    <property name="minimumNumber" value="1"/>
</module>
        

Assert statement may have side effects (formatted for browser display):

<module name="DescendantToken">
    <property name="tokens" value="LITERAL_ASSERT"/>
    <property name="limitedTokens" value="ASSIGN,DEC,INC,POST_DEC,
        POST_INC,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,DIV_ASSIGN,MOD_ASSIGN,
        BSR_ASSIGN,SR_ASSIGN,SL_ASSIGN,BAND_ASSIGN,BXOR_ASSIGN,BOR_ASSIGN,
        METHOD_CALL"/>
    <property name="maximumNumber" value="0"/>
</module>
        

The initialiser in for performs no setup (where a while statement could be used instead):

<module name="DescendantToken">
    <property name="tokens" value="FOR_INIT"/>
    <property name="limitedTokens" value="EXPR"/>
    <property name="minimumNumber" value="1"/>
</module>
        

The condition in for performs no check:

<module name="DescendantToken">
    <property name="tokens" value="FOR_CONDITION"/>
    <property name="limitedTokens" value="EXPR"/>
    <property name="minimumNumber" value="1"/>
</module>
        

A switch within a switch:

<module name="DescendantToken">
    <property name="tokens" value="LITERAL_SWITCH"/>
    <property name="limitedTokens" value="LITERAL_SWITCH"/>
    <property name="maximumNumber" value="0"/>
    <property name="minimumDepth" value="1"/>
</module>
        

A return statement from within a catch or finally block:

<module name="DescendantToken">
    <property name="tokens" value="LITERAL_FINALLY,LITERAL_CATCH"/>
    <property name="limitedTokens" value="LITERAL_RETURN"/>
    <property name="maximumNumber" value="0"/>
</module>
        

A try statement within a catch or finally block:

<module name="DescendantToken">
    <property name="tokens" value="LITERAL_CATCH,LITERAL_FINALLY"/>
    <property name="limitedTokens" value="LITERAL_TRY"/>
    <property name="maximumNumber" value="0"/>
</module>
        

Too many cases within a switch:

<module name="DescendantToken">
    <property name="tokens" value="LITERAL_SWITCH"/>
    <property name="limitedTokens" value="LITERAL_CASE"/>
    <property name="maximumDepth" value="2"/>
    <property name="maximumNumber" value="10"/>
</module>
        

Too many local variables within a method:

<module name="DescendantToken">
    <property name="tokens" value="METHOD_DEF"/>
    <property name="limitedTokens" value="VARIABLE_DEF"/>
    <property name="maximumDepth" value="2"/>
    <property name="maximumNumber" value="10"/>
</module>
        

Too many returns from within a method:

<module name="DescendantToken">
    <property name="tokens" value="METHOD_DEF"/>
    <property name="limitedTokens" value="LITERAL_RETURN"/>
    <property name="maximumNumber" value="3"/>
</module>
        

Too many fields within an interface:

<module name="DescendantToken">
    <property name="tokens" value="INTERFACE_DEF"/>
    <property name="limitedTokens" value="VARIABLE_DEF"/>
    <property name="maximumDepth" value="2"/>
    <property name="maximumNumber" value="0"/>
</module>
        

Limits the number of exceptions a method can throw:

<module name="DescendantToken">
    <property name="tokens" value="LITERAL_THROWS"/>
    <property name="limitedTokens" value="IDENT"/>
    <property name="maximumNumber" value="1"/>
</module>
        

Limits the number of expressions in a method:

<module name="DescendantToken">
    <property name="tokens" value="METHOD_DEF"/>
    <property name="limitedTokens" value="EXPR"/>
    <property name="maximumNumber" value="200"/>
</module>
        

Disallows empty statements:

<module name="DescendantToken">
    <property name="tokens" value="EMPTY_STAT"/>
    <property name="limitedTokens" value="EMPTY_STAT"/>
    <property name="maximumNumber" value="0"/>
    <property name="maximumDepth" value="0"/>
    <property name="maximumMessage"
        value="Empty statement is not allowed."/>
</module>
        

Too many fields within a class:

<module name="DescendantToken">
    <property name="tokens" value="CLASS_DEF"/>
    <property name="limitedTokens" value="VARIABLE_DEF"/>
    <property name="maximumDepth" value="2"/>
    <property name="maximumNumber" value="10"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

TreeWalker

Indentation

Description

Checks correct indentation of Java code.

The idea behind this is that while pretty printers are sometimes convenient for bulk reformats of legacy code, they often either aren't configurable enough or just can't anticipate how format should be done. Sometimes this is personal preference, other times it is practical experience. In any case, this check should just ensure that a minimal set of indentation rules is followed.

Properties

name description type default value
basicOffset how many spaces to use for new indentation level Integer 4
braceAdjustment how far braces should be indented when on the next line Integer 0
caseIndent how much to indent a case label Integer 4
throwsIndent how far a throws clause should be indented when on next line Integer 4
arrayInitIndent how much to indent an array initialisation when on next line Integer 4
lineWrappingIndentation how far continuation line should be indented when line-wrapping is present Integer 4
forceStrictCondition force strict condition in line wrapping case. If value is true, line wrap indent have to be same as lineWrappingIndentation parameter Boolean false

Examples

To configure the check:

<module name="Indentation"/>
        

To configure the check to enforce the indentation style recommended by Oracle:

<module name="Indentation">
    <property name="caseIndent" value="0"/>
</module>
        

To configure the Check to enforce strict condition in line-wrapping validation.

<module name="Indentation">
    <property name="forceStrictCondition" value="true"/>
</module>
        

Such config doesn't allow next cases:

void foo(String aFooString,
        int aFooInt) {} // indent:8 ; expected: 4; warn, because 8 != 4
        

But if forceStrictCondition = false, this code is valid:

void foo(String aFooString,
        int aFooInt) {} // indent:8 ; expected: > 4; ok, because 8 > 4
        

Package

com.puppycrawl.tools.checkstyle.checks.indentation

Parent Module

TreeWalker

TrailingComment

Description

The check to ensure that requires that comments be the only thing on a line. For the case of // comments that means that the only thing that should precede it is whitespace. It doesn't check comments if they do not end a line; for example, it accepts the following: Thread.sleep( 10 <some comment here> ); Format property is intended to deal with the "} // while" example.

Rationale: Steve McConnel in Code Complete suggests that endline comments are a bad practice. An end line comment would be one that is on the same line as actual code. For example:

a = b + c;      // Some insightful comment
d = e / f;        // Another comment for this line
        

Quoting Code Complete for the justification:

  • "The comments have to be aligned so that they do not interfere with the visual structure of the code. If you don't align them neatly, they'll make your listing look like it's been through a washing machine."
  • "Endline comments tend to be hard to format...It takes time to align them. Such time is not spent learning more about the code; it's dedicated solely to the tedious task of pressing the spacebar or tab key."
  • "Endline comments are also hard to maintain. If the code on any line containing an endline comment grows, it bumps the comment farther out, and all the other endline comments will have to bumped out to match. Styles that are hard to maintain aren't maintained...."
  • "Endline comments also tend to be cryptic. The right side of the line doesn't offer much room and the desire to keep the comment on one line means the comment must be short. Work then goes into making the line as short as possible instead of as clear as possible. The comment usually ends up as cryptic as possible...."
  • "A systemic problem with endline comments is that it's hard to write a meaningful comment for one line of code. Most endline comments just repeat the line of code, which hurts more than it helps."

McConnel's comments on being hard to maintain when the size of the line changes are even more important in the age of automated refactorings.

Properties

name description type default value
format pattern for strings allowed before the comment regular expression ^[\\s\\}\\);]*$
legalComment pattern for text allowed in trailing comments. (This pattern will not be applied to multiline comments and the text of the comment will be trimmed before matching.) regular expression (not set)

Examples

To configure the check:

<module name="TrailingComment"/>
        

To configure the check so it enforces only comment on a line:

<module name="TrailingComment">
    <property name="format" value="^\\s*$"/>
 </module>
        

Package

com.puppycrawl.tools.checkstyle.checks.indentation

Parent Module

TreeWalker

OuterTypeFilename

Description

Checks that the outer type name and the file name match. For example, the class Foo must be in a file named Foo.java.

Properties

None.

Examples

To configure the check:

<module name="OuterTypeFilename"/>
        

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

TreeWalker

UniqueProperties

Description

Checks properties files for duplicated properties.

Rationale: Multiple property keys usually appear after merge or rebase of several branches. While there are no errors in runtime, there can be a confusion due to having different values for the duplicated properties.

Properties

name description type default value
fileExtensions file type extension of the files to check. String Set properties

Examples

To configure the check:

<module name="UniqueProperties">
    <property name="fileExtensions" value="properties" />
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

Checker

AvoidEscapedUnicodeCharacters

Description

Restrict using Unicode escapes (e.g. \u221e). It is possible to allow using escapes for non-printable(control) characters. Also, this check can be configured to allow using escapes if trail comment is present. By the option it is possible to allow using escapes if literal contains only them.

Properties

name description type default value
allowEscapesForControlCharacters Allow use escapes for non-printable(control) characters. Boolean false
allowByTailComment Allow use escapes if trail comment is present. Boolean false
allowIfAllCharactersEscaped Allow if all characters in literal are escaped. Boolean false
allowNonPrintableEscapes Allow non-printable escapes. Boolean false

Examples

Examples of using Unicode:

String unitAbbrev = "μs"; //Best: perfectly clear even without a comment.
String unitAbbrev = "\u03bcs"; //Poor: the reader has no idea what this is.
        

An example of how to configure the check is:

<module name="AvoidEscapedUnicodeCharacters"/>
        

An example of non-printable(control) characters.

return '\ufeff' + content; // byte order mark
        

An example of how to configure the check to allow using escapes for non-printable(control) characters:

<module name="AvoidEscapedUnicodeCharacters">
    <property name="allowEscapesForControlCharacters" value="true"/>
</module>
        

Example of using escapes with trail comment:

String unitAbbrev = "\u03bcs"; // Greek letter mu, "s"
        

An example of how to configure the check to allow using escapes if trail comment is present:

<module name="AvoidEscapedUnicodeCharacters">
    <property name="allowByTailComment" value="true"/>
</module>
        

Example of using escapes if literal contains only them:

String unitAbbrev = "\u03bc\u03bc\u03bc";
        

An example of how to configure the check to allow escapes if literal contains only them:

<module name="AvoidEscapedUnicodeCharacters">
    <property name="allowIfAllCharactersEscaped" value="true"/>
</module>
        

An example of how to configure the check to allow non-printable escapes:

<module name="AvoidEscapedUnicodeCharacters">
    <property name="allowNonPrintableEscapes" value="true"/>
</module>
        

Package

com.puppycrawl.tools.checkstyle.checks

Parent Module

TreeWalker