Detailed Checkstyle inspection rules (a total of 138 rules)

Source: Internet
Author: User
Tags anonymous case statement coding standards eol naming convention readable return tag checkstyle
1. Annotations (note: 5)

Annotation use style (annotation style)
This check allows you to control the style of the annotations you want to use.
Missing deprecated (lack of DEPRECAD)
Check whether the Javadoc markup for the java.lang.Deprecated annotation or @deprecated exists concurrently.
Missing Override (lack of Override)
Verify that the java.lang.Override annotation appears when the Javadoc tab for {@inheritDoc} appears.
Package Annotation (Package annotation)
This check ensures that all package annotations are in the Package-info.java file.
Suppress warnings (suppression warning)
This check allows you to specify which warning messages are not allowed to be suppressed by suppresswarnings. You can also specify a tokentypes list that contains all of the warning messages that cannot be suppressed. 2. Javadoc Comments (Javadoc Note: 6)

Package Javadoc (Package note)
Check that each Java package has Javadoc annotations. By default, it allows only one Package-info.java file to be used, but it can be configured to allow the use of package.html files.
If all two files exist, an error is reported because the Javadoc tool does not allow this to happen.
Methods Javadoc (Method annotation)
Check Javadoc for the method or constructor. Unused throws are not checked by default. If you want to incorporate undeclared java.lang.RuntimeExceptions into your document, you need to set the Allowundeclaredrte property to True. The visible range you want to verify is specified by the scope property, and the default value is Scope.private. To verify other visible scopes, you need to set the scope property to the appropriate value.
If you do not want to show an error message that results from a parameter or type parameter that is not described using the PARAM tag in the annotation, you need to check the Allowmissingparamtags property. If you do not want to show an error message that is generated by declaring an exception but not using the throws tag in the comment, you need to check the Allowmissingthrowstags property. If you do not want to display an error message that results from a return statement that is not a void type but is not described using the return tag in the comment, you need to check the Allowmissingreturntag property.

A method marked by the @override annotation, its javadoc is not required. However, under Java 5, the methods in the interface cannot be tagged (already fixed in Java 6). Therefore, Checkstyle supports the use of a single {@inheritDoc} tag to replace all other tokens. For example, if the following method implements a method in an interface, then Javadoc can write this:

/* {@inheritDoc}/
public int checkreturntag (final int atagindex,
javadoctag[] atags,
int alineno)
Style Javadoc
Validates Javadoc annotations so that they are formatted. You can review the following comments: interface declarations, class declarations, method declarations, constructor declarations, variable declarations.
Type Javadoc (type annotation)
checks the Javadoc of a method or constructor. Author and version tags are not checked by default. The visible range you want to verify is specified by the scope property, and the default value is Scope.private. To verify other visible scopes, you need to set the scope property to the appropriate value. To define a format for a author tag or version tag, set the Authorformat property or Versionformat property to the specified regular expression.
If you do not want to show an error message that results from a type parameter that is not described using the PARAM tag in the annotation, you need to check the Allowmissingparamtags property.
Variable Javadoc (variable annotation)
checks to see if the variable has Javadoc annotations.
Write Tag (output markup)
to output Javadoc as information. Can be used as a style sheet to sort reports by author name. To define a format for a tag, set the Tagformat property to the appropriate regular expression. This check uses two different severity levels. When a tag is missing, use the standard severity level (Severity). When a tag exists, the additional severity level (tagseverity) is used as the reporting level. 3. Naming conventions (name Statute: 12)

Abstract class name (abstract)
Checks whether the name of the abstract class complies with the naming conventions.
Class type Parameter name (type parameter name of Class)
Checks whether the class's type parameter name complies with the naming conventions.
Constant Names (constant name)
Check that the name of the constant (the field with the static final modifier) complies with the naming conventions.
Local final Variable Names (partial final variable name)
Check that the name of the local final variable is in compliance with the naming conventions.
Local Variable Names (locally variable name)
Checks whether the name of a local variable complies with a naming convention.
Member Names (members name)
Checks whether the name of a member variable (non-static field) complies with the naming convention.
Methods Names (method name)
Checks whether the method name complies with the naming conventions.
Method type Parameter name (the type parameter name of the methods)
Checks whether the method's type parameter name complies with the naming conventions.
Package Names (package name)
Check to see if the package name complies with the naming conventions.
Parameter Names (parameter name)
Checks whether the parameter name complies with the naming conventions.
Static Variable Names (statically variable name)
Check whether the name of the static variable (the static modifier, but not the final modified field) complies with the naming convention.
Type Names (type name)
Checks to see if the name of the class complies with the naming conventions. 4. Headers (document head: 2)

Header (file header)
Checks whether the source file starts with a specified file header. The Headerfile property can specify a file that contains the header of the file you want. Alternatively, the contents of the header can be set directly in the header property instead of using an external file.

The Ignorelines property can set the line number to specify which rows in the header file are ignored when checking. This property is useful if you want to support file headers that contain the copyright date. For example, consider the following file headers:
Line 1:////////////////////////////////////////////////////////////////////
Line 2://Checkstyle:
Line 3://Checks Java source code for adherence to a set of rules.
Line 4://Copyright (C) 2002 Oliver Burn
Line 5:////////////////////////////////////////////////////////////////////
Because the year information changes over time, you can tell Checkstyle to ignore line 4th by setting the Ignorelines property to 4.
Regular Expression Header (regular expression file header)
Checks whether each row of the Java source file header matches the specified regular expression.
Explanation: In some projects, it is not enough to check for a fixed head, for example, a file header may require a single line of copyright information, but the year information will change over time.
For example, consider the following file headers:
Line 1: ^/{71} line2://checkstyle:line 2: ^//checkstyle:
Line 3: ^//Checks Java Source code for adherence to a set of rules. Line4://copyrightc\d\d\d\doliverburn Line 4: ^//Copyright C \d\d\d\d Oliver Burn
Line 5: ^//last modification by $Author. *$ LINE6:/71 Line 6: ^/{71}
Line 7:
Line 8: ^package
Line 9:
Line: ^import
Line 11:
Line 12: ^/**
Line 13: ^ * ([^/]|$)
Line 14: ^ */
Lines 1th and 6th explain how to more compactly represent the 71 '/' symbols. Line 4th indicates that the format of the year in the copyright information is four digits. Line 5th demonstrates how to add a correction control keyword to the file header. The 第12-14 row is a template for Javadoc (the 13th row is very complex and can inhibit conflicts in Javadoc annotations).5. Imports (import: 7)

Avoid Star (Demand) Imports (avoid wildcard import)
Check that no import statement uses the * symbol.
Explanation: Importing all classes from one package causes tight coupling between packages, which can cause problems when a new version of the library introduces a naming conflict.
Avoid static imports (avoid static imports)
Check that there are no static import statements.
Explanation: Importing static members can result in naming conflicts between class members. Importing static members can cause code to be poorly readable, because readers may not know exactly which class the member is in.
Illegal imports (illegal imports)
Check to see if the specified illegal package has been imported. By default, this check rejects all sun. Packages, because the program that directly uses sun. Packages is certainly not a pure Java program of 100%. To reject other packages, set the Illegalpkgs property to the list of illegal packages you specified.
Import order check (import sequence checking)
Check the order/grouping of import packages. Make sure that the packets are grouped in the order you specified (for example, Java. In the first place, javax. Second, and so on), and the packages imported in each group are listed in dictionary order. Static imports must be at the end and are also listed in dictionary order.
Redundant imports (extra imports)
Check for extra import statements. If an import statement satisfies the following conditions, it is superfluous:
1. It is a duplicate of another import statement. That is, a class has been imported more than once.
2. Import the class from the Java.lang package, for example, import java.lang.String.
3. Import classes from the current package.
Unused imports (imports not used)
Check for unused import statements. Checkstyle uses a simple and reliable algorithm to report unused import statements. If an import statement satisfies the following conditions, it is not used:
1. Not referenced in the document. This algorithm does not support wildcard import, for example, java.io.*. Most Ides use an algorithm that is very complex when checking for import statements with wildcard characters.
2. It is a duplicate of another import statement. That is, a class has been imported more than once.
3. Import the class from the Java.lang package, for example, import java.lang.String.
4. Import classes from the current package.
5. Optional: Refer to it in the Javadoc annotation. This check is turned off by default because it is a bad habit to introduce a compile-time dependency just to extract the document. For example, when the Javadoc annotation contains {@link Date}, the import java.util.Date is assumed to be referenced. To avoid introducing compile-time dependencies, you can write Javadoc annotations as {@link java.util.Date}
Import control (imported controls)
Controls which classes in each package are allowed to be imported. Can be used to ensure that the application's hierarchical rules are not illegal, especially in large projects.
The DTD file used to import control XML documents is located in the
Http://www.puppycrawl.com/dtds/import_control_1_0.dtd. It contains all the elements and attributes of the XML document described above.6. Size violations (size exceeded: 8)

Anonymous Inner classes lengths (anonymous inner class length)
Check the length of the anonymous inner class.
Explanation: If an anonymous inner class becomes very long, it is difficult to read it and it is difficult to track the process of the method. Therefore, an excessive anonymous inner class should normally be refactored into a named inner class. You can refer to page 93rd of "effective Java" written by Bloch.
Executable Statement Size (number of executable statements)
Limits the number of executable statements to a specified limit.
Maximum file Length (max.)
Check the length of the source file.
Explanation: If a source file becomes very long, it will be difficult to understand. As a result, an extended class should typically be heavily composed of several smaller, separate classes, each focusing on a specific task.
Maximum line Length (maximum length of Governor)
Check the length of each line of the source code.
Explanation: Print out the source code, or developers limit the screen display of the source space (for example, the IDE will display additional information, such as the project tree, class level, etc.), so long lines are difficult to read.
Maximum method Length (max.)
Check the length of the method and the constructor.
Explanation: If a method becomes very long, it will be difficult to understand. Therefore, an excessive approach should usually be made to form several smaller independent methods, each focusing on a specific task.
Maximum Parameters (maximum number of parameters)
Check the number of parameters for a method or constructor.
Outer Type number (outer type quantity)
Check the number of types declared in the outer (or root layer) of a file.

Explanation: It is generally considered a good practice to define only one outer type for each file.
Method Count (Total methods)
Check the number of methods declared in each type.
It includes the total number of each visible range method (private, package, protected, public). 7. Whitespace (space: 12)

Generic whitespace (generic tag spaces)
Check to see if the spaces around the generic tags < and > are compliant with the standard specifications. This statute is not configurable.

For example, the following code is legal:
List x = new ArrayList ();
List> y = new arraylist> ();

However, the following example code is not legal:
List < integer > x = new ArrayList < integer > ();
List < List < integer > > y = new ArrayList < List < Integer > > ();
Empty for initializer Pad (blank for initialization statement filler)
Check the padding for the empty for Loop initialization statement, which is whether the space can be used as a for loop to initialize the fill of the statement's empty position. If the code wraps, it is not checked, as shown in the following code:
for (
; I < J; i++, j–)
Empty for iterator pad (blank for iterator filler)
Check the padding for the empty for loop iterator, which is whether the space can be used as a fill for the empty position of the for loop iterator. If the code wraps, it is not checked, as shown in the following code:
for (iterator foo = Very.long.line.iterator ();
Foo.hasnext ();
)
No whitespace after (no spaces after the specified tag)
Check that there are no spaces after the specified tag. To disable line breaks after the specified tag, set the Allowlinebreaks property to False.
No whitespace before (no spaces before specifying tags)
There are no spaces before the specified tag is checked. To allow line breaks before the tag is specified, set the Allowlinebreaks property to True.
Operator Wrap (operator wrap)
A policy that checks the position of the operator where the code is automatically wrapped. The NL expression operator must be in a new row, and the EOL representation operator must be at the end of the current line.
Methods Parameter Pad (method parameter fill)
Checks the padding between the method definition, the constructor definition, the method call, the identifier of the constructor call, and the left parenthesis of the argument list. That is, if the identifier and the left parenthesis are on the same line, then check that the identifier needs to be followed by a space. If the identifier and the left parenthesis are not on the same line, the error is not available unless the rule is configured to allow line breaks. To use a newline character after the identifier, set the Allowlinebreaks property to True.
Paren Pad (parenthesis padding)
Check the padding policy for parentheses, that is, whether you need a space after the left parenthesis and before the closing parenthesis.
Typecast paren Pad (type conversion parenthesis fill)
Check for padding policy for parentheses for type conversions. That is, whether you need a space after the left parenthesis and before the closing parenthesis.
File tab Character (Files tab)
Check that there are no tabs (' \ t ') in the source code.

Explain:
1. In order to be able to read the source code more easily, developers should not configure the width of tabs in their text editors.
2. According to the Apache Jakarta Coding Standard: In a distributed development environment, when the submitted messages are sent to a mailing list, if you use tabs, the messages become almost impossible to read.
Whitespace after (there are spaces after the specified tag)
Checks whether the space is followed by the specified tag.
Whitespace Around (there are spaces around the specified tag)
Checks whether there are spaces around the specified tag. The Code body (code block) of an empty constructor and method in the following form:
Public MyClass () {}//Empty builder
public void Func () {}//Empty method
Can optionally be excluded from the check policy by setting the Allowemptymethods and Allowemptyconstructors properties. 8. Regexp (Regular expression: 3)

Regexpsingleline (regular expression line matching)
Checks whether a single line matches a given regular expression. Can handle any file type.

Explanation: This check can be used as a prototype check to detect common coding bad habits, such as calling Ex.printstacktrace (), System.out.println (), System.exit (), and so on.
Regexpmultiline (Regular expression multiple-line match)
Checks whether multiple rows match a given regular expression. Can handle any file type.

Explanation: This check can be used as a prototype check to detect common coding bad habits, such as calling Ex.printstacktrace (), System.out.println (), System.exit (), and so on.
Regexpsinglelinejava (Regular expression single-line Java match)
This check is a variant of the Regexpsingleline that detects whether a single line in the Java file matches a given regular expression. It supports suppressing matching operations through Java annotations. 9. Modifiers (modifier: 2)

Modifier order (modifier sequence)
Check that the order of identifiers in your code conforms to the order recommended in the chapters 8.1.1, 8.3.1 of the Java Language specification. The correct order should read as follows:
1. Public
2. Protected
3. Private
4. Abstract
5. Static
6. Final
7. Transient
8. Volatile
9. Synchronized
Native
STRICTFP.
Redundant Modifier (extra modifier)
Check for extra modifiers in the following sections:
1. Definitions of interfaces and annotations;
2 final modifier of the final class method;
3. An internal interface declaration declared as static.

Explanation: The Java Language specification strongly does not recommend using "public" and "abstract" to declare a method in an interface definition.

Variables and annotations in an interface are public, static, and final by default, so these modifiers are also superfluous.

Because annotations are a form of an interface, their fields are public, static, and final by default, just as their annotation fields are public and abstract by default.

A class that is defined as final cannot be inherited, so the final modifier of the final class's method is superfluous. Blocks (code block: 5)

Avoid Nested Blocks (avoid nested blocks of code)
Locate the nested code block, which is a code block that is used sparingly in your code.
Explanation: Embedded code blocks are usually residues of the debugging process, which can confuse readers.
Empty block (empty code blocks)
Check for empty blocks of code.
Left curly brace placement (opening curly brace position)
Check the placement of the left curly braces for the code block.
Specify the validation policy with the property option.
If you use the EOL and nlow policies, you need to consider the Maxlinelength attribute.
Need braces (curly braces required)
Check for braces around the code block, and you can check the blocks of code that are controlled by the do, else, if, for, while, etc. keywords.
Right curly brace placement (curly brace position)
Check the placement of the right curly brace for the code block of the else, try, and catch tags.
Specify the validation policy with the property option. Coding Problems (Coding questions: 43)

Avoid Inline conditionals (avoid inline conditional statements)
Detects the inline conditional statement. An example of an inline conditional statement is shown below:
String a = GetParameter ("a");
String B = (A==null | | a.length<1)? Null:a.substring (1);
Explanation: Some developers find inline conditional statements difficult to read, so their company's coding standards prohibit the use of inline conditional statements.
Covariant equals (total variable equals method)
Checks whether the Equals (Java.lang.Object) method is also overridden in a class that defines the common variable equals () method. The examination was inspired by FindBugs.
Explanation: Incorrectly defining a common equals () method without overwriting the Equals (Java.lang.Object) method may result in unpredictable run-time behavior.
Defaults comes last (default branch at end)
Check that the default in the switch statement is after all case branches.
Explanation: Java allows default to reside anywhere in a switch statement. However, if default is in the last Case branch, the code will be more readable.
Declaration Order check (Declaration sequence checking)
According to the code specification of the Java programming language, the declaration portion of a class or interface should appear in the following order:
1. Class (Static) variables. The first should be the public class variable, then the protected class variable, then the Package class variable (no access identifier), and finally the private class variable.
2. Instance variables. The first should be the public class variable, then the protected class variable, then the Package class variable (no access identifier), and finally the private class variable.
3. Construction Device
4. Methods
Empty Statement (empty statement)
Detects whether there is an empty statement (that is, a separate symbol) in the code.
equals avoid null (avoid calling the Equals method of NULL references)
Check the Equals () comparison method to see if any combination of string constants is on the left.
This check also handles String.equalsignorecase () calls (this warning can be suppressed).

Explanation: The Equals () method that invokes the string constant can avoid potential nullpointerexception. Similarly, it is often found that a null pointer check is performed before the Equals () method is invoked, although in the following example there is no need to do so.

For example:
String nullstring = null;
Nullstring.equals ("my_sweet_string");

This piece of code should be refactored to:
String nullstring = null;
"My_sweet_string". Equals (nullstring);

Limitation: If the Equals method is overridden, or a common-variable equals method is defined, and the method is not implemented correctly (that is, the result returned by S.equals (T) is different from the result returned by T.equals (s)), Overwriting the objects and parameters that invoke the method can produce unpredictable results.

The Java autoboxing feature has an impact on how this check is implemented. Prior to the Java 5 version, all ident + Ident object stitching did not cause nullpointerexception, even if it was a null pointer. This examination already contains these conditions. They do simple processing, as if they were surrounded by the string.valueof () method, which stitching up the null string.

The following example will cause a nullpointerexception, which is the result of the autoboxing function:
Integer i = null, j = null;
String number = "5"
Number.equals (i + j);
Since it is difficult to determine which type of object is being spliced, all ident stitching will be considered unsafe.
Equals and Hashcode (Equals method and Hashcode method)
Check that the class that overrides the Equals () method also overrides the Hashcode () method.
Explanation: The Equals () method and the Hashcode () method Convention are bound to have the same hash code for equal objects. Therefore, as long as you override the Equals () method, you must overwrite the Hashcode () method at the same time to ensure that you can use your class in a hash based collection.
Explicit initialization (Explicit initialization)
Checks whether a member of a class or object is explicitly initialized to the default value of a member-owning type (the default value for the object reference is NULL, the default value for the value and character type is 0, and the default value for the Boolean type is false).
Explanation: Each instance variable is initialized two times and initialized to the same value. Java initializes each instance variable to its default value (0 or null) before executing any of the initialization actions specified in the code. So in this case, X will be initialized to 2 times, and bar will be initialized to null two times. Therefore, this is somewhat inefficient. This coding style is a continuation of the C + + coding style, which shows that the developer is not really sure that Java can initialize the instance variable to its default value.
Fall through (spanning branch)
Check to see if there are any spanning branches in the switch statement. If a case branch's code lacks a break, return, throw, or continue statement, it can cause a spanning branch.
This check can be used to suppress a warning by special annotations. By default, you can suppress a warning when you add notes (case-sensitive), such as "Fallthru", "Fall Through", "Fallthrough", "Falls through", "Fallsthrough", in case branch codes that span branches. Comments that contain the above words must be on one line and must be in the last line of the current case branch code, or on the same line as the case statement, as shown in the following code:
switch (i) {
Case 0:
i++; Fall through

Case 1:
i++;
Falls through
Case 2: {
i++;
}
Fallthrough
Case 3:
i++;
/* Fallthru */case 4:
i++
Break
}
Note: This check assumes that there is no unreachable code in the case branch code.
Final local Variable (final locals)
Checks whether local variables that never change the value are declared final. This check can also be configured to check whether the unmodified parameters are declared final.
When configured to check for parameters, this check ignores the parameters in the interface method and abstract method.
Hidden field (hidden fields)
Checks whether local variables or parameters will obscure fields defined in the same class.
Illegal instantiation (illegal instantiation)
Check for illegal instantiation operations, preferably using factory methods.
Explanation: Depending on the project, for some classes, it might be better to create a class instance through a factory method than to invoke the Class builder.
A simple example is the Java.lang.Boolean class. To conserve memory and CPU cycles, it is best to use predefined constants true and false. The call to the constructor should be replaced by the call to the Boolean.valueof () method.

Some projects with extreme performance requirements may require other classes to use factory methods to improve the efficiency of caching or object pooling.
Illegal catch (illegal exception capture)
Never allow to capture Java.lang.Exception, Java.lang.Error, java.lang.RuntimeException behavior.
Explanation: Inexperienced developers often simply catch exception exceptions and try to handle a variety of exception types. This unfortunately causes the code to accidentally capture system exceptions such as NullPointerException, Outofmemoryerrors, and so on.
Illegal Throws (illegal exception thrown)
This check can be used to ensure that a type cannot declare a specified exception type. Never allow a declaration to throw java.lang.Error or java.lang.RuntimeException.
Illegal tokens (illegal marking)
Check for illegal tags.
Explanation: A language feature can often cause code to be difficult to maintain or difficult for developers to understand. In some frameworks, other features may not be recommended, for example, it is best not to use local methods in EJB components.
Illegal tokens text (illegal tag literal)
Check to see if there are any illegal markup text.
Illegal type (illegal type)
Check your code for specific classes that are not used as types in variable declarations, return values, and parameters. Includes a format check feature that does not allow abstract classes by default.
Explanation: Helps reduce the coupling between entity classes. In addition, an abstract class should be considered a simple base-class implementation of an interface, so it cannot be the type itself.
Inner Assignment (internal assignment)
Checks whether there are assignment statements in the subexpression, such as string s = integer.tostring (i = 2);.
Explanation: This check ignores the for loop code, and all remaining assignment operations should be in their own top-level statements for readability. In the above internal assignment code, it is difficult to see where the variable is assigned.
JUnit test Case (JUnit testing cases)
Ensure that the setup (), teardown () method has the correct name, no arguments, the return type is void, public or protected.
Also ensure that the suite () method has the correct name, no parameters, the return type is junit.framewotk.Test, and is public and static.
Explanation: Developers often mistakenly name these methods and do not realize that these methods are not invoked.
Magic Number (phantom)
Check that the code contains "magic Numbers", which are numeric literals that are not defined as constants. By default,-1, 0, 1, 2 are not considered to be magic numbers.
Missing constructor (missing builder)
Check that the class (in addition to the abstract class) defines a constructor instead of relying on the default constructor.
Missing switch defaults (missing switch default branch)
Check to see if the switch statement contains a default clause.
Explanation: It is often a good idea to introduce a default branch in each switch statement. Even if the developer is convinced that all of the current possible branches can be overwritten, this should also be expressed in the default branch, for example, by using an assertion. This approach allows the code to handle future modifications, such as introducing a new type in an enumerated type.
Modified Control Variable (modify controlling variable)
Check that the control variable for the For loop is not modified in the for code block. The sample code is as follows:
for (int i = 0; i < 1; i++) {
i++;
}
Explanation: If you modify the control variables in the loop body, the program flow becomes more difficult to track. You can replace the for loop with a while loop.
Multiple string literals (multiple string constants)
Checks whether the same string constant appears more than once in a single file.
Explanation: Repeating code makes maintenance more difficult, so it's a good idea to replace multiple occurrences with a constant.
Multiple Variable declaration (multiple variable Declaration)
Check whether each variable is declared with a single line of statements.
Explanation: Chapter 6.1 of the Sun Coding Statute recommends that a variable be declared using a single line of statements.
Nested for Depth (for nesting depth)
Limit the number of nested layers for A for loop (the default is 1).
Nested if Depth (if nesting depth)
Limit the number of nested layers of the If-else code block (the default is 1).
Nested try Depth (try nesting depth)
Limit the number of nesting layers of the try code block (the default is 1).
No Clone (no Clone method)
Checks whether the clone () method in the object class is overwritten.

Explanation: The Clone () method relies on a set of strange and hard to follow rules that do not work in all cases. Therefore, it is difficult to properly overwrite the clone () method. Here are some reasons why you should avoid using the Clone () method.
Classes that support the Clone method should cloneable the interface beforehand, but the cloneable structure does not contain a clone method. Therefore, it does not force a clone method to be overwritten.
The Cloneable interface forces the object's clone method to work correctly. If this interface is not implemented, then the object's Clone method throws a clonenotsupportedexception. Classes that are not decorated with the final keyword must return the object returned by the calling Super.clone () method. Classes decorated with the final keyword can use a constructor to create a cloned object that differs from the non-final class.
If a parent class does not implement the Clone method correctly, all subclasses will be doomed to fail if they call the Super.clone () method.
If a class contains a reference to a Mutable object, after the Super.clone () method is invoked in the clone method of the class, the object reference must be replaced with a copy of the previously mutable object.
The Clone method does not properly handle a Mutable object reference decorated with the final keyword, because the final reference cannot be assigned a value.
If a parent class overrides the Clone method, all subclasses must provide a correct clone implementation.
In some cases, there are two alternatives to the Clone method that can be used, one using a copy constructor and the other using a static factory method to return a copy of an object. Both methods are simpler and do not conflict with fields decorated with the final keyword. They do not force the calling client to handle clonenotsupportexception. They are all of a type and therefore do not require any type conversions. Finally, they are more flexible because they can handle interface types, not just entity classes.

Sometimes, you cannot use a copy constructor or static factory as an alternative to the Clone method. The following example illustrates the limitations of a copy builder or a static factory. Suppose that square is a subclass of shape.
Shape S1 = new Square ();
System.out.println (S1 instanceof Square); True
... Suppose the code here doesn't know that S1 is a square type object, which is the beauty of polymorphism, but the code wants to copy the square object declared as a shape type, shape is the parent of square ...
Shape s2 = new shape (S1); Using the copy constructor
SYSTEM.OUT.PRINTLN (S2 instanceof Square); False
An effective solution (no need to know all of the subclasses and do not perform a large number of type conversions) should be as shown in the following code (assuming the correct clone method is implemented):
Shape s2 = S1.clone ();
SYSTEM.OUT.PRINTLN (S2 instanceof Square); True
Just remember, if you need this type of polymorphic clone, then a properly implemented clone method might be the best choice.

This check is almost exactly the same as {@link Nofinalizercheck}.
No Finalizer (no Finalize method)
Verify that the Finalize () method is defined in the class.
Package Declaration (Package Declaration)
Make sure that a class has a package declaration and (optionally) the package name to match the directory name in which the source code file resides.
Explanation: A class that is in an empty package is not able to be imported. Many novice developers have not noticed this.
Parameter Assignment (parameter assignment)
Assigning values to parameters is not allowed.
Explanation: Assigning values to parameters is often considered a lack of programming experience. It is often cumbersome to force developers to declare their parameters final. This check ensures that parameters are never assigned, which is good for both sides.
Redundant Throws (extra Throws)
Check to see if an extra exception is declared in the throws clause, such as a repeating exception, an unchecked exception, or a subclass of an exception that has been declared thrown.
Require this (requires this)
Check that the code uses "this.", that is, by default, references to instance variables and methods of the current object should be invoked explicitly through the form "This.varname" or "this.methodname (args)".
Return Count (Total return)
Limit the number of return statements. The default value is 2. You can omit to check the specified method (the Equals () method is ignored by default).
Explanation: Too many return points may indicate that the code is trying to handle too many businesses and may be difficult to understand.
Simplify Boolean Expression (simplified Boolean expression)
Check for overly complex Boolean expressions. Can now discover things like if (b = = true), B | | True,!false, and other types of code.
Explanation: Complex Boolean logic can make code difficult to understand and maintain.
Simplify Boolean return (simplified Boolean returned value)
Check for overly complex Boolean type return statements. For example, the following code:
if (valid ())
return false;
Else
return true;
Can be written as:
return!valid ();
This examination is drawn from the PMD rule.
String Literal Equality (strict constant equality comparison)
Checks whether the comparison of string objects uses the = = or!= operator.
Explanation: Java Novice Programmers often use code similar to the following:
if (x = = "Something")
In fact, they want to express the following meaning:
if ("Something". Equals (x))
Superclone (Parent class Clone method)
Checks whether an overridden clone () method invokes the Super.clone () method.
Reference: Object.clone ().
Superfinalize (Parent-type Finalize method)
Checks whether a covered finalize () method invokes the Super.finalize () method.
Reference: Clean unused objects.
Trailing array Comma (array trailing comma)
Checks whether the initialization of the array contains a trailing comma.
Int[] A = new int[]
{
1,
2,
3,
};
If both the left curly brace and the right curly brace are on the same line, this check allows no trailing commas to be added. As shown below:
return new int[] {0};

Explanation: Adding a trailing comma can make it easier to change the order of elements, or to add new elements at the end.
Unnecessary parentheses (unnecessary parentheses)
Check to see if unnecessary parentheses are used in the code.
One Statement per line (a single statement)
Check if each line has only one statement. The following line will be identified as an error:
x = 1; y = 2; There are two statements 12 in a row . Class Design: 8

Designed for Extension (design Extensibility)
checks to see if the class is extensible. More precisely, it enforces a programming style in which the parent class must provide an empty "handle" for the subclass to implement them.
The exact rule is that a private, non-static method in a class that can be inherited by subclasses must be:
1. Abstract method, or
2. Final method, or
3. There is an empty implementation
Explanation: This API design style can protect the parent class from being corrupted by the quilt. The disadvantage is that the flexibility of subclasses is limited, especially because they do not prevent the execution of parent code, but this also means that subclasses do not destroy the state of the parent class because they forget to invoke the method of the parent class. (Personal understanding: Do not allow the method of the class to overwrite)
Final class (final)
checks whether a class that has a private constructor is declared final.
Inner Type last (Final declaration of internal types)
checks whether nested/internal types are declared at the bottom of the current class (after all the method/field declarations).
Hide Utility class constructor (hidden tool class Builder)
ensures that the tool class (only static methods and fields in the API Class) has no public structure

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.