What is FindBugs? _ Tools

Source: Internet
Author: User
Tags lowercase scalar throwable checkstyle
The Java Code flaw Automatic analysis tool mainly has: Findbugs, PMD and Checkstyle tool. This article focuses on the use of FindBugs and briefly mentions the use of PMD and Checkstyle tools. 1 FindBugs is what.

FindBugs is a Java bytecode static analysis tool that can help Java engineers improve code quality and eliminate hidden flaws.

FindBugs check the class or JAR file to compare the bytecode with a set of bug patterns to discover possible problems.

With static analysis tools, software can be analyzed without actually running the program. Rather than analyzing the form or structure of a class file to determine the intent of the program, FindBugs typically uses the Visitor pattern for analysis (more information on Visitor patterns).

2 What FindBugs can do.

The FindBugs provides 35 detectors to detect possible defects in bytecode. Can do the main things are: 2.1 Find hash equals mismatch

Find several issues related to the implementation of equals () and hashcode (). These two methods are important because almost all of the collection-based classes call them---List, Map, set, and so on. In general, this detector looks for two different types of problems:

① when a class overrides the Equals () method of an object, but does not rewrite its Hashcode method, or the opposite.

② defines a co-variant version of the Equals () or CompareTo () method. For example, the Bob class defines its equals () method as Boolean equals (Bob), which overrides the Equals () method defined in the object. Because Java code resolves overloaded methods at compile time, this version of the method that is almost always defined in the object at run time, rather than the one defined in Bob (unless explicitly casting the argument of the Equals () method to the Bob type). Therefore, when an instance of this class is put into any one of the class collections, the Object.Equals () version of the method is used, not the version defined in Bob. In this case, the Bob class should define a equals () method that accepts a parameter of type Object.

20090325 (Wednesday) added:

With respect to the Equals () method and the Hashcode () method, these two methods are generally conjoined. A class inherits from the object class, and if you override one of the two methods, you must override the other method (in general, overriding the Equals () method, and you should be aware of overriding the Hashcode () method).

2.2 Detection: Ignoring method return values

This detector looks for a place in the code that ignores the return value of a method that should not be ignored.   A common example of this is when you call the string method, for example: Java code string astring = "Bob";   Astring.replace (' B ', ' P '); if (Astring.equals ("Pop"))

This error is very common. On line 2nd, the programmer thinks he has replaced all B in the string with P. That's true, but he forgets that the string is immutable. All such methods return a new string and never change the recipient of the message.

20090325 (Wednesday) Add: String replace (char Oldchar, char Newchar)
Returns a new string resulting from replacing all occurrences of the Oldchar in this string with Newchar.

Note: When executing to the third sentence, there are two strings, one is astring, the value is "Bob", and another is the new string "Pop" returned by the Replace method.

2.3 Detection: null refers to null-based dereference (dereference) and redundancy comparison

This detector looks for two types of problems. It looks for cases where the code path will or may cause null pointer exceptions, and it also looks for redundancy comparisons to NULL. For example, if two comparison values are null, they are redundant and may indicate code errors.   FindBugs detects a similar error when it is possible to determine that one value is null and the other is not NULL, for example: Java code person person = Amap.get ("Bob");   if (person!= null) {person.updateaccesstime (); String name = Person.getname ();

In this example, if the Map on line 1th does not include a person named "Bob," a null pointer exception appears when the 5th line asks for the name of someone. Because FindBugs does not know if the map contains "Bob", it marks line 5th as a possible null pointer exception.

20090325 (Wednesday) added:

Null pointer exception, most of the case is null.***, want to do some operation on a null object, will inevitably result in null pointer exception. This exception should be the most frequent exception in Java encoding and should be given sufficient attention (more non-null check in code).

2.4 Detection: Read fields before initialization

This detector looks for fields that were read before initialization in the constructor.       This error is usually caused by using a field name instead of a constructor parameter, such as reading an uninitialized field in a constructor: Java code public class Thing {private List actions;          Public Thing (String startingactions) {StringTokenizer tokenizer = new StringTokenizer (startingactions);          while (Tokenizer.hasmoretokens ()) {Actions.Add (Tokenizer.nexttoken ()); }       }   }

In this example, line 6th produces a null pointer exception because the variable actions have not yet been initialized.

20090325 (Wednesday) added:

This problem, should not exist, eclipse occurs in this situation will automatically error, compile pass but, should not be excuse me findbugs.

2.5 name Check

Tests for Standard Java command specifications: Variable names should not be too short, method names should not be too long, class names should start with lowercase letters, methods and field names should start with lowercase letters, and so on.

2.6 Unused Code checks

Finds private and local variables that have never been used, statements that are not executed, private methods that have never been invoked, and so on.

20090325 (Wednesday) added:

Check for extra code. Private field or private method, other people can not use directly, if in this class are not used, that still put on this side why. (In fact, the starting point for private fields and private methods is only used for this class.) )

2.7 Nested Checks

For example, a switch statement should have a default block, you should avoid deeply nested if blocks, you should not assign values to parameters, and you should not make an equal comparison of the double value.

20090325 (Wednesday) added:

1.switch statements in each case, you should not have a break statement, or it will take place through the phenomenon;

2. As for the default block, must also have some, this is fallback capital preservation.

3. Deep nested If blocks should be avoided: the depth is too deep and the logical structure of the program is not clearly understood, at which point you can consider organizing the logic or splitting it into multiple methods.

4. Parameters should not be assigned a value: Of course, since you use the accept parameters, in the method and the other people passed over the value to the value of, this is called what AH (or do not pass this parameter in, is the so-called: employing not suspect, the suspect does not).

5. The double value should not be compared equally: well, this is to note that a double is not like an integer, it is imprecise (the decimal part is simulated by 0101), so it is not possible to compare two double numbers directly. Generally compare whether the difference between the two is less than a certain value (for example, 0.0001, which is equivalent to the 4th digit after the decimal point), if set up, you can think that the two are "equal".

2.8 Import Statement Check

Check the problem with the import statement, as if a class was imported two times or imported into a Java.lang class.

20090325 (Wednesday) added:

The same class import once know, why the superfluous, import the second time, thankless.

Import Java.lang: Eldest brother, this package does not import can directly use, you why.

2.9 JUnit Test Check

Find specific questions about test cases and test methods, such as the correct spelling of method names, and whether the suite () method is static and public.

2.10 string Check

Find common problems that you encounter when handling strings, such as repeating string literals, calling the string constructor, and calling the ToString () method on a string variable.

20090325 (Wednesday) added:

Duplicate string scalar: string scalar here, it should be said that the string constants, this string constant ah, is stored in the memory of the data Segment, a general one is enough, there is no need to repeat the definition.

Call the ToString () method on a string variable: When printing out a string variable, the default call is the ToString () method, which returns itself, why should it be shown?

Call String Constructor ... I suddenly did not see what is wrong with this ...

2.11 Bracket Check

Checks whether the for, if, while and ELSE statements use parentheses.

20090325 (Wednesday) added:

This problem is also to note that at the beginning only a sentence, from the implementation effect, add this bracket is no problem.

But without parentheses, it's a bad habit. There is a hidden problem: The future append code, directly after the original sentence, the purpose is to add code in the statement block, but because there is no parenthesis, if you forget parentheses, so the logic of the code is obviously wrong.

So, even if the statement in the code snippet is only one sentence, add parentheses to avoid pitfalls.

2.12 Code size Check

Test for too-long methods, classes with too many methods, and similar problems with refactoring.

2.13 Finalization function Check

Because the Finalize () method is not so prevalent in the Java language, their rules of use are detailed, but people are relatively unfamiliar with them. Such checks look for various problems with the Finalize () method, such as empty finalization functions, the Finalize () method of calling other methods, explicit calls to finalize (), and so on.

2.14 Cloning Check

The new rule for the Clone () method. All classes overriding the Clone () method must implement Cloneable, and the Clone () method should call Super.clone (), and the Clone () method should declare the clonenotsupportedexception exception thrown, even if it is not actually thrown An exception, so be it.

20090325 (Wednesday) Add: Protected Object Clone ()
Creates and returns a copy of this object.

Protected Object Clone () throws Clonenotsupportedexception

2.15 coupling Check

Find signs of excessive coupling between classes, such as too many imported content, use subclasses when the superclass or interface is sufficient, and too many fields, variables, and return types in the class.

2.16 Anomaly Check

Check for exceptions: You should not declare the method and throw the java.lang.Exception exception, you should not use the exception for flow control, you should not capture throwable, and so on.

20090325 (Wednesday) added:

Should not capture Throwable: This guy is a catch-all anomaly, why are you catching it?

2.17 Log Check

Find improper use of java.util.logging.Logger, including non-final status (nonfinal), non-static loggers, and multiple loggers in a class.

2.18 Open-close Inspection

Check for file or communication and forget about close.

20090325 (Wednesday) added:

The main meaning is: resources (file resources, connection resources) used, but finally remember to help people to turn off the resources, the beginning and end.

2.19 Other Checks

A list of other defects can be found in: Defect list

2.20 Building your own set of rules

You can build your own set of rules

Note: For more information on the use and analysis of other tools, please refer to:

Http://www.cnblogs.com/tester2test/archive/2006/06/08/420832.html

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.