Checkstyle Document Sorting

Source: Internet
Author: User
Tags case statement perl script checkstyle

 
About checkstyle
Checksytle is a code format check tool. It can check the code according to the configured encoding rules.
For example, naming variables that comply with the specifications and a good program style.
If your project manager says at a meeting, "I hope the code we write is like a one-person code !" Checkstyle is definitely the correct choice, and checkstyle is mainly used in the following three aspects.
1 ant: write a script and call checkstyle. It is generally used as part of the build script.
2. Eclipse: Call checkstyle as a plug-in. It is generally used for self-check by developers.
3 cvs: You need to write a Perl script to call checkstyle. When code is submitted to CVS, The checkstyle check is triggered. If the Code does not meet the requirements, it cannot be submitted.
The following describes only Eclipse: As a plug-in, checkstyle is called for self-check by developers.

2. Install checkstyle in myeclipse 8.6
1. Download The checkstyle4.4.1 installation package and decompress it,
Test the two folders features and Plugins in COM. atlassw. Tools. Eclipse. checkstyle_4.4.1-bin to the myeclipse8.6 installation directory.
For example, under the two folders corresponding to D: \ Program Files \ genuitec \ common
Plugins can have multiple folders.

Ii. Modification
D: \ ProgramFiles \ genuitec \ MyEclipse-8.6 \ Configuration \ org. Eclipse. Equinox. simpleconfigurator folder bundles.info file,
Add the following two lines at the end:
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

The approximate configuration format is: file name, version, path, 4, false (I did not check what it meant)
3. Restart myeclipse
<! -- [Endif] -->
The checkstyle plugin is successfully installed.
3. Create a checkstyle custom rule
I. default rules
By default, checksyle uses the Custom Rules of The sun_checks.xml file. If you use the custom rules of this file to check the code, thousands of errors will be found.

Ii. Custom Rules
Write a custom file
<! -- [Endif] -->
Set the associated custom file in myeclipse and set it as the default detection configuration file.
<! -- [Endif] -->
3. Writing and meaning of custom rules.
<! Doctype module public
"-// Puppy crawl // DTD Check Configuration 1.2 // en"
Http://www.puppycrawl.com/dtds/configuration_1_2.dtd>
<Module name = "checker">
<! -- Repeat the code check, more than 8 lines are considered repeated, UTF-8 format
This check must be placed before the "treewalker" node. Otherwise
Checkclipse cannot be used. (In ant)
-->
<Module name = "strictduplicatecode">
<Property name = "min" value = "8"/>
<Property name = "charset" value = "UTF-8"/>
</Module>
<Module name = "treewalker">
<! -- Javadoc check -->
<! -- Check all interfaces and Classes
<Module name = "javadoctype"/> -->
<! -- Check the javadoc of all methods without declaring runtimeexception
<Module name = "javadocmethod">
<Property name = "allowundeclaredrte" value = "true"/>
</Module> -->

<! -- Check the javadoc of a Variable
<Module name = "javadocvariable"/> -->
<! -- For naming checks, they all use sun's official rules. -->
<! -- Check the class name (class or interface) -->
<Module name = "typename"/>
<! -- Variable check -->
<Module name = "membername"/>
<! -- Check method name -->
<Module name = "methodname"/>
<! -- Method parameter name -->
<Module name = "parametername"/>
<! -- Check the constant name -->
<Module name = "constantname"/>
<! -- Check the length -->
<! -- The file length cannot exceed 1500 rows -->
<Module name = "filelength">
<Property name = "Max" value = "1500"/>
</Module>
<! -- No more than 120 words per line -->
<Module name = "linelength">
<Property name = "Max" value = "120"/>
</Module>
<! -- The number of methods cannot exceed 30 -->
<Module name = "methodlength">
<Property name = "tokens" value = "method_def"/>
<Property name = "Max" value = "300"/>
</Module>
<! -- The number of parameters of a method cannot exceed 3. -->
<Module name = "parameternumber">
<Property name = "Max" value = "3"/>
</Module>
<! -- Redundant keywords -->
<Module name = "redundantmodifier"/>
<! -- Check the region -->
<! -- Blank areas cannot appear -->
<Module name = "emptyblock"/>
<! -- Braces must be used for all regions. -->
<Module name = "needbraces"/>
<! -- Extra parentheses -->
<Module name = "avoidnestedblocks">
<Property name = "allowinswitchcase"
Value = "true"/>
</Module>
<! -- Encoding check -->
<! -- Empty statements are not allowed -->
<Module name = "emptystatement"/>
<! -- Each class implements equals () and hashcode () -->
<Module name = "mongoshashcode"/>
<! -- Do not use switch -->
<Module name = "illegaltoken">
<Property name = "tokens"
Value = "literal_switch"/>
</Module>
<! -- Do not assign internal values -->
<Module name = "innerassignment"/>
<! -- Never tolerate magic count -->
<Module name = "magicnumber">
<Property name = "tokens" value = "num_double"/>
</Module>
<! -- The cyclic control variable cannot be modified -->
<Module name = "modifiedcontrolvariable"/>
<! -- Redundant throw -->
<Module name = "redundantthrows"/>
<! -- Do not use unsimplified conditional expressions -->
<Module name = "simplifybooleanexpression"/>
<! -- Do not use unsimplified Boolean return values -->
<Module name = "simplifybooleanreturn"/>
<! -- String comparison is unavailable! = And = -->
<Module name = "stringliteralequality"/>
<! -- If a maximum of three layers can be nested -->
<Module name = "nestedifdepth">
<Property name = "Max" value = "3"/>
</Module>
<! -- Try can be nested at most at Layer 1 -->
<Module name = "nestedtrydepth"/>
<! -- The clone method must call Super. Clone () -->
<Module name = "superclone"/>
<! -- Finalize must call Super. Finalize () -->
<Module name = "superfinalize"/>
<! -- Cannot catch java. Lang. Exception -->
<Module name = "illegalcatch">
<Property name = "illegalclassnames"
Value = "Java. Lang. Exception"/>
</Module>
<! -- The core method of junittestcase exists. -->
<Module name = "junittestcase"/>
<! -- Up to three return statements in a method -->
<Module name = "returncount">
<Property name = "Max" value = "3"/>
</Module>
<! -- Do not assign values to method parameters -->
<Module name = "parameterassignment"/>
<! -- A string with the same content is not allowed -->
<Module name = "multiplestringliterals"/>
<! -- The same row cannot have multiple declarations -->
<Module name = "multiplevariabledeclarations"/>
<! -- Various metrics -->
<! -- The complexity of a Boolean expression cannot exceed 3 -->
<Module name = "booleanexpressioncomplexity"/>
<! -- Abstract coupling of class data, no more than 7 -->
<Module name = "classdata=actioncoupling"/>
<! -- Class dispersion complexity, no more than 20 -->
<Module name = "classfanoutcomplexity"/>
<! -- The Branch complexity of the function cannot exceed 10 -->
<Module name = "cyclomaticcomplexity"/>
<! -- Npath complexity, no more than 200 -->
<Module name = "npathcomplexity"/>
<! -- Miscellaneous -->
<! -- Disable system. Out. println -->
<Module name = "genericillegalregexp">
<Property name = "format" value = "SYSTEM \. Out \. println"/>
<Property name = "ignorecomments" value = "true"/>
</Module>
<! -- Do not use comments with code peers -->
<Module name = "trailingcomment"/>
</Module>
<! -- Check the translation file -->
<Module name = "Translation"/>
</Module>

Iv. Explanation of some custom rules
A. duplicate code
This check should be placed under the <Module name = "checker"> node. Repeated code check allows you to find the code that has been copied/past.
The typical disadvantage of repeated code is to increase the maintenance cost, because you need to modify a bug many times and test it more times.
When the code only differs in indentation, compare the code line by line and report whether the code is repeated.
Ignore import. Other content, including Javadoc and blank rows at the method interval, will be included and compared.
Use default check:
<Module name = "strictduplicatecode"/>
There are more than 15 lines of the same Code and the file encoding is a UTF-8 check:
<Module name = "strictduplicatecode">
<Property name = "min" value = "15"/>
<Property name = "charset" value = "UTF-8"/>
</Module>
This check will include blank rows in the check range. If the Code contains more than a blank row defined by the "min" attribute, an error is returned.
For example, if "min" = 8, nine consecutive blank lines exist in the code, an error is returned.
 
B. Various metrics
Various metrics During encoding are very theoretical. I haven't seen such content in other documents in China, so I copied the content. Let's learn it together.
(1) Complexity of boolean expressions
Limit the number of &, | and ^ In a Boolean expression. It makes the code clearer and easier to troubleshoot and maintain. Default check:
<Module name = "booleanexpressioncomplexity"/>

A maximum of seven operators are allowed:
<Module name = "booleanexpressioncomplexity">
<Property name = "Max" value = "7"/>
</Module>

"Max" specifies the maximum number of allowed operators. The default value is 3.

(2) Abstract coupling of class data
Classdata=actioncoupling
Check the number of instances of other classes created in one class. This type of coupling is not caused by inheritance or object-oriented aggregation.
In general, if any abstract data type uses other abstract data types as its own member, it will produce data abstraction coupling (DAC );
In other words, if a class uses instances of other classes as its own member variables, it will produce abstract data coupling.
The higher the coupling degree, the more complicated the data structure of the system.
Shen Zhi Note: that is to say, if too many other classes are used in a class, it will certainly increase the complexity of the system. The less classes you use, the less coupling.
Check that the coupling degree is at most 5:
<Module name = "classdata=actioncoupling">
<Property name = "Max" value = "5"/>
</Module>
 
The "Max" attribute specifies the maximum number. The default value is 7.
(3) Class dispersion complexity
Classfanoutcomplexity
The number of other classes that a class depends on. The square of this number is also displayed to indicate the minimum number of modifications required. The dispersion complexity is up to 10:
<Module name = "classfanoutcomplexity">
<Property name = "Max" value = "10"/>
</Module>

The "Max" attribute specifies the maximum number. The default value is 20.
(4) Branch complexity of functions
Cyclomaticcomplexity
Make sure that the branch complexity of the function does not exceed the limit.
This complexity refers to the investigation of most functions (constructor, general method, static initial function, and instance initialization function)
If, while, do, ,? :, Catch, switch, case statement, and the number of &, | operators are calculated.
It indicates the minimum number of branches passing a function, and thus shows the number of tests to be performed.
Generally, 1-4 is excellent, and 5-7 is qualified. 8-10 depends on the situation. Reconstruction is required for more than 11 items!
The branch complexity is 7 at most:
<Module name = "cyclomaticcomplexity">
<Property name = "Max" value = "7"/>
</Module>
 
The "Max" attribute specifies the maximum number. The default value is 10.
(5). npath complexity
Npathcomplexity
The npath measure calculates the number of executable branches of a function. It attaches great importance to the nesting of conditional statements and boolean expressions composed of multiple parts (such as a & B, c | D, and so on ).
Nejmeh said his team had an informal npath Convention: no more than 200. Functions Whose npath exceeds this number must be decomposed.
Complexity cannot exceed 40:
<Module name = "npathcomplexity">
<Property name = "Max" value = "40"/>
</Module>
The "Max" attribute specifies the maximum number. The default value is 200.

C. Miscellaneous
Miscellaneous that are difficult to classify
(1). Forbidden expressions
Check for code problems. You can use this check to control the use of some code. For example, do not use the "system. Out. println" check in the Code:
<Module name = "genericillegalregexp">
<Property name = "format" value = "SYSTEM \. Out \. println"/>
</Module>

The "format" attribute specifies the format of the regular expression for invalid characters. ("." Is represented by "\."). shows the complete Attribute Table.

(2) Press enter at the end of the file
Check whether there is a carriage return at the end of the file.
Principle: The source file and text file should generally end with a new line (Press ENTER.
Especially when source code control systems such as CVs are used. CVS even displays a warning if it does not end with a new line.
This check should be placed under the <Module name = "checker"> node.
Default check:
<Module name = "ewlineatendoffile"/>
Check for Linux-style line breaks:
<Module name = "newlineatendoffile">
<Property name = "lineseparator" value = "lf"/>
</Module>

Check only the Java, XML, or Python files:
<Module name = "newlineatendoffile">
<Property name = "fileextensions" value = "Java, XML, Py"/>
</Module>

(3). Main function not commented out
Check the main function that has not been commented out
Principle: The main () function is usually used for debugging. After the appearance of JUnit, main () is reduced, but some people prefer to use it.
After debugging, we can easily forget to delete it. It modifies the API and increases the size of the class or jar file.
Therefore, all main methods should be deleted or commented out except for normal program portals.

Default check:
<Module name = "uncommentedmain"/>

You can set the "excludedclasses" attribute to not check a class. The type is regular expression, and the default value is "^ $ ". If you do not want to check the class whose name ends with "Main", you can do this:
<Module name = "uncommentedmain">
<Property name = "excludedclasses" value = "^ main &"/>
</Module>

(4). L in upper case
Check and make sure that all constants contain uppercase letters. That is, if "L" is not used in constants, then "L" is used. For example, long constants must end with "L.
This is consistent with sun coding specification 3.10.1. The lowercase letter L is too similar to the number 1.
<Module name = "upperell"/>

(5). Declare the array Style
Check the definition of the array type. There are two styles: Java: String [] ARGs or C/C ++: String ARGs []
Check whether the Java style is used:
<Module name = "arraytypestyle"/>

Check whether the C style is used:
<Module name = "arraytypestyle">
<Property name = "javastyle" value = "false"/>
</Module>

(6). indent
Check Java code indentation
Because the indentation of "tab" in different text editors is different, it is best to use spaces.
Default Configuration: four spaces are indented, and the braces for the new line are: 0. The case of a new line contains four spaces.
<Module name = "indentation"/>
(7). A required string
Make sure that a string check exists in the code. This check does not care where it appears, as long as it appears.
For example, check that the Code must contain the word "Copyright", "This code is copyrighted ":
<Module name = "requiredregexp">
<Property name = "format" value = "this code is copyrighted"/>
</Module>

The "format" attribute specifies the regular expression of a required string. The default value 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.