Checks whether files end with a new line.
Rationale: Any source files and text files in general should end with a newline character, especially when using SCM systems such as CVS. CVS will even print a warning when it encounters a file that doesn't end with a newline.
name | description | type | default value |
---|---|---|---|
lineSeparator | type of line separator | One of "system" (system default), "crlf" (Windows-style), "cr" (Mac-style) and "lf" (Unix-style) | system default |
fileExtensions | file type extension of the files to check. | String Set | all files |
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>
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 property format.
name | description | type | default value |
---|---|---|---|
format | pattern to check | regular expression | TODO: |
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.
To configure the check:
<module name="TodoComment"/>
To configure the check for comments that contain WARNING:
<module name="TodoComment"> <property name="format" value="WARNING"/> </module>
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.
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 |
Checks for uncommented main() methods (debugging leftovers).
Rationale: A main() method is often used for debug puposes. When debugging is finished, developers often forget to remove the method, which changes the API and increases the size of the resulting class/jar file. With the exception of the real program entry points, all main() methods should be removed/commented out of the sources.
name | description | type | default value |
---|---|---|---|
excludedClasses | pattern for qualified names of classes which are allowed to have a main method. | regular expression | ^$ |
To configure the check:
<module name="UncommentedMain"/>
To configure the check to allow main method for all classes with "Main" name:
<module name="UncommentedMain"> <property name="excludedClasses" value="\.Main$"/> </module>
Checks that long constants are defined with an upper ell. That is ' L' and not 'l'. This is in accordance to the Java Language Specification, Section 3.10.1.
looks a lot like 1.
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[])
name | description | type | default value |
---|---|---|---|
javaStyle | Controls whether to enforce Java style (true) or C style (false). | Boolean | true |
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>
Check that method/constructor/catch block parameters 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.
name | description | type | default value |
---|---|---|---|
tokens | blocks to check | subset of tokens METHOD_DEF, CTOR_DEF, LITERAL_CATCH | METHOD_DEF, CTOR_DEF |
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>
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 recomend using other checks when they provide the desired funcionality. All in all, this check just works on the level of an abstract tree and knows nothing about language structures.
name | description | type | default value |
---|---|---|---|
tokens | token types to check | subset of tokens declared in TokenTypes | empty set |
limitedTokens | set of tokens with limited occurances as descendants | subset of tokens declared in TokenTypes | empty set |
minimumDepth | the mimimum 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 minimum count not reached | String | "descendant.token.min" |
maximumMessage | error message when maximum count exceeded | String | "descendant.token.max" |
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>
Initialiser in for performs no setup (use while instead?):
<module name="DescendantToken"> <property name="tokens" value="FOR_INIT"/> <property name="limitedTokens" value="EXPR"/> <property name="minimumNumber" value="1"/> </module>
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>
Switch within 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>
Return 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>
Try within 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>
Limit 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>
Limit 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>
Disallow 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>
Checks correct indentation of Java Code.
The basic idea behind this is that while pretty printers are sometimes convienent 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 are followed.
name | description | type | default value |
---|---|---|---|
basicOffset | how many spaces to use for new indentation level | Integer | 4 |
braceAdjustment | how far brace should be indented when on next line | Integer | 0 |
caseIndent | how much to indent a case label | Integer | 4 |
To configure the check:
<module name="Indentation"/>
To configure the check to enforce indentation style recommended by Sun:
<module name="Indentation"> <property name="caseIndent" value="0"/> </module>
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 line, i.e. it accept 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 justfication:
His comments on being hard to maintain when the size of the line changes are even more important in the age of automated refactorings.
name | description | type | default value |
---|---|---|---|
format | pattern for string allowed before comment. | regular expression | ^[\\s\\}\\);]*$ |
legalComment | pattern for text of trailing comment which is allowed. (this patter will not be applied to multiline comments and text of comment will be trimmed before matching) | regular expression | (not set) |
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>
A check that makes sure that a specified pattern exists, exists less than a set number of times, or does not exist in the file.
This check combines all the functionality provided by RegexpHeader, GenericIllegalRegexp and RequiredRegexp, except supplying the regular expression from a file.
It differs from them in that it works in multiline mode. It's regular expression can span multiple lines and it checks this against the whole file at once. The others work in singleline mode. Their single or multiple regular expressions can only span one line. They check each of these against each line in the file in turn.
Note: Because of the different mode of operation there may be some changes in the regular expressions used to achieve a particular end.
In multiline mode...
Note: Not all regexp engines are created equal. Some provide extra functions that others do not and some elements of the syntax may vary. This check makes use of the java.util.regex package, please check its documentation for details of how to construct a regular expression to achive a particular goal.
Note: When entering a regular expression as a parameter in the xml config file you must also take into account the xml rules. e.g. if you want to match a < symbol you need to enter <. The regular expression should be entered on one line.
name | description | type | default value |
---|---|---|---|
format | pattern | regular expression | $^ (empty) |
message | message which is used to notify about violations, if empty then default(hard-coded) message is used. | String | ""(empty) |
illegalPattern | Controls whether the pattern is required or illegal. | Boolean | false |
duplicateLimit | Controls whether to check for duplicates of a required pattern, any negative value means no checking for duplicates, any positive value is used as the maximum number of allowed duplicates, if the limit is exceeded errors will be logged. | Integer | -1 |
errorLimit | Controls the maximum number of errors before the check will abort. | Integer | 100 |
ignoreComments | Controls whether to ignore matches found within comments. | Boolean | false |
The following examples are mainly copied from the other 3 checks mentioned above, to show how the same results can be acheived using this check in place of them.
To use like RequiredRegexp :
An example of how to configure the check to make sure a copyright statement is included in the file:
The statement.
// This code is copyrighted
The check.
<module name="Regexp"> <property name="format" value="// This code is copyrighted"/> </module>
Your statement may be multiline.
// This code is copyrighted // (c) MyCompany
Then the check would be.
<module name="Regexp"> <property name="format" value="// This code is copyrighted\n// \(c\) MyCompany"/> </module>
Note: To search for parentheses () in a regular expression you must escape them like \(\). This is required by the regexp engine, otherwise it will think they are special instruction characters.
And to make sure it appears only once:
<module name="Regexp"> <property name="format" value="// This code is copyrighted\n// \(c\) MyCompany"/> <property name="duplicateLimit" value="0"/> </module>
It can also be useful to attach a meaningful message to the check:
<module name="Regexp"> <property name="format" value="// This code is copyrighted\n// \(c\) MyCompany"/> <property name="message" value="Copyright"/> </module>
To use like GenericIllegalRegexp :
An example of how to configure the check to make sure there are no calls to System.out.println:
<module name="Regexp"> <!-- . matches any character, so we need to escape it and use \. to match dots. --> <property name="format" value="System\.out\.println"/> <property name="illegalPattern" value="true"/> </module>
You may want to make the above check ignore comments, like this:
<module name="Regexp"> <property name="format" value="System\.out\.println"/> <property name="illegalPattern" value="true"/> <property name="ignoreComments" value="true"/> </module>
An example of how to configure the check to find trailing whitespace at the end of a line:
<module name="Regexp"> <property name="format" value="[ \t]+$"/> <property name="illegalPattern" value="true"/> <property name="message" value="Trailing whitespace"/> </module>
Note: The difference between this and the example given for GenericIllegalRegexp is necessary because \s and $ both match the newline character ("\n").
An example of how to configure the check to find case-insensitive occurrences of "debug":
<module name="Regexp"> <property name="format" value="(?i)debug"/> <property name="illegalPattern" value="true"/> </module>
Note: The (?i) at the beginning of the regular expression tells the regexp engine to ignore the case.
There is also a feature to limit the number of errors reported. When the limit is reached the check aborts with a message reporting that the limit has been reached. The default limit setting is 100, but this can be change as shown in the following example.
<module name="Regexp"> <property name="format" value="(?i)debug"/> <property name="illegalPattern" value="true"/> <property name="errorLimit" value="1000"/> </module>
To use like RegexpHeader :
To configure the check to verify that each file starts with the following multiline header.
Note the following:
// Copyright (C) 2004 MyCompany // All rights reserved
<module name="Regexp"> <property name="format" value="\A// Copyright \(C\) \d\d\d\d MyCompany\n// All rights reserved"/> </module>
A more complex example. Note how the import and javadoc multilines are handled, there can be any number of them.
/////////////////////////////////////////////////////////////////////// // checkstyle: // Checks Java source code for adherence to a set of rules. // Copyright (C) 2004 Oliver Burn // Last modification by $Author A.N.Other$ /////////////////////////////////////////////////////////////////////// package com.puppycrawl.checkstyle; import java.util.thing1; import java.util.thing2; import java.util.thing3; /** * javadoc line 1 * javadoc line 2 * javadoc line 3 */
<module name="Regexp"> <property name="format" value="\A/{71}\n// checkstyle:\n// Checks Java source code for adherence to a set of rules\.\n// Copyright \(C\) \d\d\d\d Oliver Burn\n // Last modification by \$Author.*\$\n/{71}\n\npackage [\w\.]*;\n\n (import [\w\.]*;\n)*\n/\*\*\n( \*[^/]*\n)* \*/"/> </module>
More examples:
The next 2 examples deal with the following example java source file:
/* * PID.java * * Copyright (c) 2001 ACME * 123 Some St. * Somewhere. * * This software is the confidential and proprietary information of ACME. * ("Confidential Information"). You shall not disclose such * Confidential Information and shall use it only in accordance with * the terms of the license agreement you entered into with ACME. * * $Log: config_misc.xml,v $ * Revision 1.7 2007/01/16 12:16:35 oburn * Removing all reference to mailing lists * * Revision 1.6 2005/12/25 16:13:10 o_sukhodolsky * Fix for rfe 1248106 (TYPECAST is now accepted by NoWhitespaceAfter) * * Fix for rfe 953266 (thanks to Paul Guyot (pguyot) for submitting patch) * IllegalType can be configured to accept some abstract classes which * matches to regexp of illegal type names (property legalAbstractClassNames) * * TrailingComment now can be configured to accept some trailing comments * (such as NOI18N) (property legalComment, rfe 1385344). * * Revision 1.5 2005/11/06 11:54:12 oburn * Incorporate excellent patch [ 1344344 ] Consolidation of regexp checks. * * Revision 1.3.8.1 2005/10/11 14:26:32 someone * Fix for bug 251. The broken bit is fixed */ package com.acme.tools; import com.acme.thing1; import com.acme.thing2; import com.acme.thing3; /** * * <P> * <I>This software is the confidential and proprietary information of * ACME (<B>"Confidential Information"</B>). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with ACME.</I> * </P> * * © copyright 2002 ACME * * @author Some Body */ public class PID extends StateMachine implements WebObject.Constants { /** javadoc. */ public static final int A_SETPOINT = 1; . . . } // class PID
This checks for the presence of the header, the first 16 lines.
Note the following:
<module name="Regexp"> <property name="format" value="\A/\*\n \* (\w*)\.java\n \*\n \* Copyright \(c\) \d\d\d\d ACME\n \* 123 Some St\.\n \* Somewhere\.\n \*\n \* This software is the confidential and proprietary information of ACME\.\n \* \("Confidential Information"\)\. You shall not disclose such\n \* Confidential Information and shall use it only in accordance with\n \* the terms of the license agreement you entered into with ACME\.\n \*\n \* \$Log: config_misc.xml,v $ \* \Revision 1.7 2007/01/16 12:16:35 oburn \* \Removing all reference to mailing lists \* \ \* \Revision 1.6 2005/12/25 16:13:10 o_sukhodolsky \* \Fix for rfe 1248106 (TYPECAST is now accepted by NoWhitespaceAfter) \* \ \* \Fix for rfe 953266 (thanks to Paul Guyot (pguyot) for submitting patch) \* \IllegalType can be configured to accept some abstract classes which \* \matches to regexp of illegal type names (property legalAbstractClassNames) \* \ \* \TrailingComment now can be configured to accept some trailing comments \* \(such as NOI18N) (property legalComment, rfe 1385344). \* \ \* \Revision 1.5 2005/11/06 11:54:12 oburn \* \Incorporate excellent patch [ 1344344 ] Consolidation of regexp checks. \* \\n(.*\n)*([\w|\s]*( class | interface )\1)"/> <property name="message" value="Correct header not found"/> </module>
This checks for the presence of a copyright notice within the class javadoc, lines 24 to 37.
<module name="Regexp"> <property name="format" value="(/\*\*\n)( \*.*\n)*( \* <P>\n \* <I> This software is the confidential and proprietary information of\n \* ACME \(<B>"Confidential Information"</B> \)\. You shall not\n \* disclose such Confidential Information and shall use it only in\n \* accordance with the terms of the license agreement you entered into\n \* with ACME\.</I>\n \* </P>\n \*\n \* © copyright \d\d\d\d ACME\n \*\n \* @author .*)(\n\s\*.*)*/\n[\w|\s]*( class | interface )"/> <property name="message" value="Copyright in class/interface Javadoc"/> <property name="duplicateLimit" value="0"/> </module>
Note: To search for things that mean something in xml, like < you need to escape them like <. This is required so the xml parser does not act on them, but instead passes the correct character to the regexp engine.