Checkstyle Document Collation

Source: Internet
Author: User
Tags perl script checkstyle

Checkstyle Introduction
Checksytle is a code format checking tool. It can check the code according to the set coding rules.
such as the specification of variable naming, good program style and so on.
If your project manager says in a meeting, "I hope the code we write is like a person's writing." "When, with Checkstyle is definitely the right choice, checkstyle mainly used in the following three aspects."
1 ant: Scripting, calling Checkstyle. Typically used to build a part of a script.
2 Eclipse: Invoke Checkstyle as a plug-in. Typically used by developers to check themselves.
3 CVS: You need to write a Perl script call Checkstyle. A checkstyle check is triggered when the code is submitted to CVS and cannot be committed if it does not meet the requirements.
The following only covers eclipse: calling Checkstyle as a plug-in for developers to check themselves.


2.checkStyle installation in MyEclipse 8.6
First, download to the checkStyle4.4.1 installation package and decompression,
Com.atlassw.tools.eclipse.checkstyle_4.4.1-bin inside the two folders features and plugins inside the folder to MyEclipse8.6 installation directory
For example: D:\Program Files\genuitec\common inside the corresponding two folders
Description: Plugins can have more than one folder, no matter how many are tested in


Ii. modification
D:\ProgramFiles\Genuitec\MyEclipse-8.6\configuration\ Bundles.info files under the Org.eclipse.equinox.simpleconfigurator folder,
At the end, add two lines of configuration:
Com.atlassw.tools.eclipse.checkstyle,4.4.1,file:/d:/program files/genuitec/common/
Plugins/com.atlassw.tools.eclipse.checkstyle_4.4.1/,4,false
Net.sf.eclipsecs.stats,1.0.4,file:/d:/program files/genuitec/common/plugins/net.sf.eclipsecs.stats_1.0.4/,4, False




Configuration of the approximate format is: file name, version, path, 4,false (specific I did not check what it means)
Third, restart MyEclipse
<!--[endif]-->
The Checkstyle plug-in was successfully installed.
3. Development of Checkstyle Custom rules
One, default rule
Checksyle default is to use the custom rules of the Sun_checks.xml file, if you use this file custom rules to check the code will find thousands of errors.


Two, custom rules
Write a custom file
<!--[endif]-->
Set the custom file on the association in MyEclipse and set as the default instrumentation profile.
<!--[endif]-->
Three The wording and meaning of the custom rule.
<! DOCTYPE Module Public
"-//puppy crawl//dtd Check Configuration 1.2//en"
"Http://www.puppycrawl.com/dtds/configuration_1_2.dtd" >
<module name= "Checker" >
<!--duplicate code checking, over 8 lines are considered duplicate, UTF-8 format
This check must be placed in front of the "Treewalker" node, otherwise
cannot be used in Checkclipse. (Can be under ant)
-->
<module name= "Strictduplicatecode" >
<property name= "min" value= "8"/>
<property name= "CharSet" value= "UTF-8"/>
</module>
<module name= "Treewalker" >
<!--Javadoc inspection-->
<!--check all interface and class
<module name= "Javadoctype"/>-->
<!--Check all the methods of Javadoc, you can not declare runtimeexception
<module name= "Javadocmethod" >
<property name= "Allowundeclaredrte" value= "true"/>
</module>-->


<!--check Javadoc for a variable
<module name= "javadocvariable"/>-->
<!--name checks, all of which use Sun's official rules. -->
<!--class name (classes or interface) Check-->
<module name= "TypeName"/>
Inspection of <!--variables-->
<module name= "MemberName"/>
< inspection of!--method name-->
<module name= "methodname"/>
The parameter name--> of the <!--method
<module name= "ParameterName"/>
<!--constant name checking-->
<module name= "Constantname"/>
Inspection of the length of the <!---->
<!--file length not exceeding 1500 lines-->
<module name= "Filelength" >
<property name= "Max" value= "1500"/>
</module>
<!--no more than 120 characters per line-->
<module name= "LineLength" >
<property name= "Max" value= "/>"
</module>
<!--method No more than 30 lines-->
<module name= "Methodlength" >
<property name= "tokens" value= "Method_def"/>
<property name= "Max" value= "/>"
</module>
The number of parameters for the <!--method is no more than 3. -->
<module name= "Parameternumber" >
<property name= "Max" value= "3"/>
</module>
<!--extra keyword-->
<module name= "Redundantmodifier"/>
<!--inspection of the area-->
<!--no blank areas-->
<module name= "Emptyblock"/>
<!--use curly braces for all areas. -->
<module name= "Needbraces"/>
<!--extra bracket-->
<module name= "Avoidnestedblocks" >
<property name= "Allowinswitchcase"
Value= "true"/>
</module>
<!--code inspection-->
<!--no empty statements-->
<module name= "Emptystatement"/>
<!--each class implements Equals () and hashcode ()-->
<module name= "Equalshashcode"/>
<!--don't use switch-->
<module name= "Illegaltoken" >
<property name= "Tokens"
Value= "Literal_switch"/>
</module>
<!--do not allow internal assignment-->
<module name= "Innerassignment"/>
<!--must not tolerate magic number-->
<module name= "MagicNumber" >
<property name= "tokens" value= "num_double"/>
</module>
<!--loop control variable cannot be modified-->
<module name= "Modifiedcontrolvariable"/>
<!--redundant throw-->
<module name= "Redundantthrows"/>
<!--do not use conditional expressions that are not simplified-->
<module name= "Simplifybooleanexpression"/>
<!--do not use Boolean return values that are not simplified-->
<module name= "Simplifybooleanreturn"/>
<!--string comparisons cannot be made with!= and = =-->
<module name= "Stringliteralequality"/>
<!--if most nested 3-layer-->
<module name= "Nestedifdepth" >
<property name= "Max" value= "3"/>
</module>
<!--try to be nested up to 1 layers-->
<module name= "Nestedtrydepth"/>
The <!--Clone method must invoke the Super.clone ()-->
<module name= "Superclone"/>
<!--finalize must call the Super.finalize ()-->
<module name= "Superfinalize"/>
<!--can't catch java.lang.Exception-->
<module name= "Illegalcatch" >
<property name= "Illegalclassnames"
Value= "Java.lang.Exception"/>
</module>
The core methods of <!--junittestcase exist. -->
<module name= "Junittestcase"/>
<!--a maximum of 3 return--> in one method
<module name= "Returncount" >
<property name= "Max" value= "3"/>
</module>
<!--do not assign values to the parameters of the method-->
<module name= "Parameterassignment"/>
<!--not allowed to have the same content string-->
<module name= "Multiplestringliterals"/>
<!--cannot have multiple declarations on the same line-->
<module name= "Multiplevariabledeclarations"/>
<!--various measurement-->
<!--the complexity of Boolean expressions, no more than 3-->
<module name= "Booleanexpressioncomplexity"/>
Abstract coupling of <!--class data, not exceeding 7-->
<module name= "classdataabstractioncoupling"/>
<!--class of dispersed complexity, no more than-->
<module name= "Classfanoutcomplexity"/>
The branch complexity of the <!--function, no more than ten-->
<module name= "Cyclomaticcomplexity"/>
<!--Npath complexity, no more than-->
<module name= "Npathcomplexity"/>
<!--Miscellaneous-->
<!--prohibit the use of System.out.println-->
<module name= "Genericillegalregexp" >
<property name= "format" value= "System\.out\.println"/>
<property name= "Ignorecomments" value= "true"/>
</module>
<!--don't use annotations with code peers-->
<module name= "Trailingcomment"/>
</module>
<!--check translation documents-->
<module name= "translation"/>
</module>


Iv. interpretation of partial custom rules
A. Duplicate code
This check should be placed under <module name = "Checker" > node. Duplicate code checking allows you to find code that has been copy/past out.
A typical drawback of repeating code is increasing the cost of maintenance because you need to modify a bug many times and test more times.
When the code is simply indented, it compares them line by row and reports whether they are duplicated.
Ignoring import, other content, including Javadoc, blank lines of method intervals, etc. are included and compared.
Use default check:
<module name= "Strictduplicatecode"/>
The same line of code is more than 15 lines, and the file encoding is UTF-8 check:
<module name= "Strictduplicatecode" >
<property name= "min" value= "/>"
<property name= "CharSet" value= "UTF-8"/>
</module>
This inspection will count the blank lines in the scope of the inspection. An error is also made if there is more than a blank line defined by the "min" attribute in your code.
For example, "min" = 8 o'clock, if there are 9 consecutive blank lines in the code, an error is found.

b Various measures
The various measurements in coding are very theoretical. I have not seen such content in other documents in China, so the content is basically copied, we learn together.
(1). The complexity of Boolean expressions
Limit the &&amp in a Boolean expression; and ^ 's number. You can make your code look clearer, easy to debug, and maintain. Default check:
<module name= "Booleanexpressioncomplexity"/>


Allow up to 7 operators:
<module name= "Booleanexpressioncomplexity" >
<property name= "Max" value= "7"/>
</module>


where "Max" specifies the maximum number of allowed operators, the default is 3.


(2). Abstract coupling of class data
Classdataabstractioncoupling
Checks the number of instances of other classes established in a class. This type of coupling is not caused by inheritance or object-oriented aggregation.
In general, any abstract data type, if the other abstract data type as its own member, then it will produce data abstraction coupling (DAC);
In other words, if a class uses an instance of another class as its own member variable, then data abstraction coupling is generated.
The higher the coupling degree, the more complex the data structure of the system is.
Shen thought note: In other words, if you use too many other classes in a class, you will definitely increase the complexity of the system. The less you use the other classes, the less the coupling.
The degree of coupling is up to 5 check:
<module name= "Classdataabstractioncoupling" >
<property name= "Max" value= "5"/>
</module>

Where the max attribute specifies the maximum number, and the default is 7.
(3). Dispersion complexity of class
Classfanoutcomplexity
The number of other classes that a class relies on. The square of this number is also displayed to indicate the minimum number of modifications required. The maximum dispersion complexity is 10:
<module name= "Classfanoutcomplexity" >
<property name= "Max" value= "ten"/>
</module>


Where the max attribute specifies the maximum number, and the default is 20.
(4). Branch complexity of a function
Cyclomaticcomplexity
Make sure that the branch complexity of the function does not exceed the limit.
This complexity is done by examining most functions (constructors, general methods, static initial functions, instance initialization functions)
If, while, does, for,? :, catch, switch, case statements and && The number of operators to be computed.
It represents the smallest number of branches through a function, and thus the number of tests that need to be performed.
Generally 1-4 is excellent and 5-7 is qualified. 8-10 See the situation refactoring. More than 11 must be reconstructed immediately.
Branch complexity is up to 7 checks:
<module name= "Cyclomaticcomplexity" >
<property name= "Max" value= "7"/>
</module>

Where the max attribute specifies the maximum number, and the default is 10.
(5). Complexity of Npath
Npathcomplexity
The Npath metric calculates the number of branches that can be executed by a function. It attaches great importance to the nested and multiple-component Boolean expressions of conditional statements (e.g., a&&b, c| | D, etc.).
Nejmeh said his team had an informal Npath agreement: no more than 200. A function that npath over this number must be decomposed.
Less than 40 complexity:
<module name= "Npathcomplexity" >
<property name= "Max" value= "/>"
</module>
Where the max attribute specifies the maximum number, and the default is 200.


C. Miscellaneous
Difficult to classify miscellaneous
(1). An expression that is forbidden to use
A check for a code problem. This check allows users to control the use of certain code. For example, to prohibit the use of "System.out.println" checks in your code:
<module name= "Genericillegalregexp" >
<property name= "format" value= "System\.out\.println"/>
</module>


Where the Format property specifies the formatting of the regular expression for the illegal character. ("." With "\." ), as shown in the complete property sheet.


(2). Carriage return at end of file
Check to see if there is a carriage return at the end of the file.
Rationale: Source files and text files should generally end with a new line (carriage return).
Especially when using a source code control system such as CVS. If you do not end with a new row as a file, CVS may even display a warning.
This check should be placed under <module name = "Checker" > node.
Default check:
<module name= "Ewlineatendoffile"/>
Check for line breaks with Linux style:
<module name= "Newlineatendoffile" >
<property name= "LineSeparator" value= "lf"/>
</module>




Check only Java, XML, or Python files:
<module name= "Newlineatendoffile" >
<property name= "Fileextensions" value= "Java, XML, py"/>
</module>


(3). A main function that is not commented out
Check for main functions that are not commented out
Principle: the main () function is usually used for debugging, and main () is reduced after JUnit appears, but some people prefer to use it.
We can easily forget to delete it after we have finished debugging. It modifies the API and increases the volume of class or jar files.
So, except for the normal program entrance, all main methods should be deleted or commented out.


Default check:
<module name= "Uncommentedmain"/>


You can set the "Excludedclasses" property to not check a class, the type is a regular expression test, and the default value is "^$". If you do not want to check the class that ends with "Main" in the name, you can do this:
<module name= "Uncommentedmain" >
<property name= "excludedclasses" value= "^main&"/>
</module>


(4). Capital L
Check to make sure that the L in all constants is uppercase. That is, "L" instead of "L" in a constant, such as a long constant, ends with "L".
This is consistent with the Sun code specification 3.10.1. The lowercase letter L is too much like the number 1.
<module name= "Upperell"/>


(5). Declaring the style of an array
Check the definition of the array type. There are two styles: Java-style: string[] args or C + +-style: String args[]
Check to see if the Java style is used:
<module name= "Arraytypestyle"/>


Check to see if the C style is used:
<module name= "Arraytypestyle" >
<property name= "Javastyle" value= "false"/>
</module>


(6). Indentation
Check the indentation of Java code
Because "tab" is indented differently under different text editors, it's best to use spaces.
Default configuration: Basic indent 4 spaces, new line braces: 0. Case 4 spaces for the new row.
<module name= "Indentation"/>
(7). A string that must appear
Make sure that there is a check for a string in your code. The check doesn't care where it appears, as long as it appears.
For example, check that the code must appear with the word copyright, "This code is copyrighted":
<module name= "Requiredregexp" >
<property name= "format" value= "This code is copyrighted"/>
</module>


The Format property specifies the regular expression of the string that must appear. The default is null. "^$"

<!--[endif]-->


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.