Using FindBugs to reduce the number of bugs in the code

Source: Internet
Author: User
Tags coding standards instance method integer numbers

Function of FindBugs

After developing some code, developers can use FindBugs to check code defects. This improves the code quality and reduces the number of bugs reported by testers.

Static analysis tools promise to identify existing defects in the code without the effort of developers. Of course, if you have years of writing experience, you will know that these commitments are not necessarily fulfilled.
 
Code defect category

According to the nature of the defect, it can be roughly divided into the following categories:

· Bad practice Bad practices
· Correctness may be incorrect
· Dodgy bad code
· Experimental experiment
· Internationalization: Internationalization
· Malicious code vulnerility Malicious code vulnerability
· Multithreaded correctness multithreading
· Performance problems

The FindBugs official website also provides some cases:

Http://findbugs.sourceforge.net/bugDescriptions.html

How to use FindBugs?

You can use FindBugs in three ways: 1) GUI, 2) IDE plug-in, and 3) Ant script.

The first two methods are described below:


1) use FindBugs GUI

 
Download 1.1

Download Address: Linux: http://prdownloads.sourceforge.net/findbugs/findbugs-3.0.1.tar.gz? Download

Windows: http://prdownloads.sourceforge.net/findbugs/findbugs-3.0.1.zip? Download

1.2 Installation

The installation method is simple. You only need to extract the package. Configure the environment variable FINDBUGS_HOME after installation.

Linux: export FINDBUGS_HOME =/home/username/findbugs

Windows:



1.3 Start

Switch the directory to the findbugs/bin directory:

Cd $ findbugs_home/bin or cd % findbugs_home %/bin

Run the findbugs script:

./Findbugs or findbugs. bat

In this way, you can start findbugs GUI:

 
Note:

· The class packages and directories to be analyzed, which are generally the class packages to be analyzed

· The Auxiliary class is the dependent jar package.

· The source file directory is the directory where the source code is located

2) used as the IDE plug-in

Developers often use this method. Supported IDEs include Eclipse, NetBeans, and Intellij IEDA.

The following describes how to use it in Eclipse.

Download plug-ins

Download Address: http://sourceforge.net/projects/findbugs/files/findbugs%20eclipse%20plugin/

Install

Directly decompress the package to the eclipse/plugins directory.


 

Filter configuration

Open the Perferences configuration of Eclipse:


 
Analysis bugs:

 



FindBugs Learning Summary


Today, the code quality emphasizes that the findBugs check should be performed before the java code is submitted to SVN. Although I also have the findBugs plug-in based on the menu, for more comprehensive learning and more efficient use, I searched and learned how to use findbugs.


Check principle

Findbugs is a static analysis tool that checks class or JAR files and compares bytecode with a set of defect modes to identify possible problems. Findbugs comes with detectors, including more than 60 Bad practice, more than 80 Correctness, 1 Internationalization, 12 Malicious code vulnerability, 27 Multithreaded correctness, 23 Performance, and 43 Dodgy. We can also configure inspection rules by ourselves (which checks are performed and not checked), or implement unique verification rules by ourselves (you need to inherit its interfaces to customize a specific bug mode, writing your own validation class is an advanced technique ).

Static checks in white-box tests generally check the encoding standard specification and error list. Coding standards are often set by the team based on their own experience and style. Nowadays, many IDE tools will remind you in real time whether the code style is correct when editing the code. The error list is generally a potential bug in the code. Although there is no syntax error in writing a code, there may be errors, such as causing a Thread deadlock. These are all error lists that should be checked. The following operations can be performed on static checks:

1. Code Lookup:

Programmers can extract code from each other for further query.
These experiences are grouped into a list based on the summary report during the query, which serves as the basis for the next code query.
This method is characterized by being Manual, discussed by many people, and easy to operate, but with low efficiency.

2. Code scanning

Use software to scan our code to find potential problems. There are many commercial tools that can be scanned, such as Parasoft JTest, Software Analyzer, and pclint. Usually different tools are used in different languages. Of course, there are also many open-source tools. Findbugs is recommended for java. Findbugs can be run in ANT/GUI/ECLIPSE environments, and you can also write your own detectors with complete functions. We can collect our own or others' development experience and make it a detector to improve the Findbugs detection system. Software scanning is characterized by high machine scanning efficiency, but not flexible enough, and more responsible for expansion.


Comparison of Java static check tools

Tools

Purpose

Check items

FindBugs

Check. class

Find Potential bugs in javabytecode (. class file) based on the concept of Bug Patterns

This mainly checks the bug patterns in bytecode, such as NullPoint null pointer check, the resource is not properly closed, and the same string judgment error (=, rather than equals).

PMD

Check source files

Check potential problems in Java source files

It mainly includes:

Empty try/catch/finally/switch statement Block

Unused local variables, parameters, and private methods

Null if/while statement

Too complex expressions, such as unnecessary if statements

Complex class

CheckStyle

Check source files

Main concern format

Check whether the Java source file is consistent with the code specification.

It mainly includes:

Javadoc comments

Naming rules

Useless Imports

Size measurement, such as the method that is too long

Necessary spaces are missing. Whitespace

Duplicate code



Use and configuration

This article describes how to use Eclipse.

FindBugs is a program that can be found in Java programs. It is used to find the code in the "Bug Patterns" list. Bug Patterns indicates an instance of code that is likely to be incorrect.

Open Bug Details View Windows => Show View => Other... => FindBugs => BugDetails


In the Package Explorer or Navigator view, right-click your Java project and choose Find Bugs from the shortcut menu, the sub-menu items include "Find Bugs" and "Clear Bug Markers", as shown in the following figure:

Let's create a simple Test file Test. java with the following content:

Public class Test {private String [] name; public String [] getName () {return name;} public void setName (String [] name) {this. name = name ;}}


Click "Find Bugs". The following progress box is displayed during running:

After running, the following warning information is added to Problems:

The warning information after FindBugs is displayed not only in the Problems view, but also in the source code markup box. In the source code editor, we can see the warning identifier, as shown in the following figure:


When the cursor points to your warning code, there will be an error message, similar to the error or warning message prompts of Eclipse.

If you select the Problems in the Problems View, the code editor will switch to the corresponding code to facilitate code modification based on the corresponding prompts.


In the Problems View, right-click the corresponding question entry and choose Show Bug Details from the shortcut menu, as shown in the following figure:


Click it to switch to the Bug Details view to display more detailed prompts.

Of course, when you click the icon with a warning message in the code editing window, it will automatically switch to the Bud Details window to view the detailed warning information, as shown in the following figure.


Based on the detailed information here, you can get the FindBugs warning information about your code and corresponding solutions. According to the prompts, you can quickly and conveniently modify the code.

As prompted, we changed the code to the following, and then run the code without warning.

Public class Test {private String [] name; public String [] getName () {String [] temp = name; return temp;} public void setName (String [] name) {String [] temp = name; this. name = temp ;}}


Configure FindBugs

Right-click your project and choose Properties> FindBugs>


Configurable information includes settings for the four options shown in the preceding figure:

1. Run FindBugs Automatically switch

When this option is selected, FindBugs will automatically run when you modify the Java class. If you set the Eclipse automatic compilation switch, FindBugs will run after you modify the Java file and save it, and display the corresponding information.

If this option is not selected, you can run FindBugs to check your code each time you need it.

2. Minimum priority to report option

This option is used to display the information of the selected level. You can select either Low, Medium, or High, which is similar to the level setting of Log4J. For example:

If you select the High option, only the prompt information of the High level will be displayed.

If you select the Medium option, only Medium and High-level prompts are displayed.

If you select the Low option, all levels of prompt information will be displayed.

3. Enable bug categories option

Here are some options for displaying Bug categories:

Correctness about code Correctness

Performance about code Performance

Internationalization about code Internationalization

Multithreaded correctness

Style

Malicious code vulnerability

For example, if you do not select the Style check box, the warning information related to the Style category will not be displayed. Others are similar.

4. Select bug patterns to check for selection item

Here you can select the relevant Bug Pattern entries to be checked

You can see in the Bug codes, Detector name, and Detector description what content to check. You can select or remove the corresponding check conditions as needed.

III. Details

Findbugs is a static analysis tool that checks class or JAR files and compares bytecode with a set of defect modes to identify possible problems. Findbugs comes with detectors, including more than 60 Bad practice, more than 80 Correctness, 1 Internationalization, 12 Malicious code vulnerability, 27 Multithreaded correctness, 23 Performance, and 43 Dodgy.

Bad practice Bad practices

Some bad practices are listed below:

HE: the class defines equals (), but does not have hashCode (); or the class defines equals (), but uses

Object. hashCode (); or the class defines hashCode (), but does not have equals (); or the class defines hashCode (), but uses Object. equals (); class inherits equals (), but uses Object. hashCode ().

SQL: the execute method of Statement calls a very large number of strings; or the Prepared Statement is generated by a very large number of strings.

DE: method termination or non-handling exceptions. Generally, exceptions should be handled, reported, or thrown by methods.

Correctness

Code that may cause errors:

NP: the null pointer is referenced. In the abnormal path of the method, the null pointer is referenced. The method does not check whether the parameter is null. The null value is generated and referenced; the null value is generated and referenced in the abnormal path of the method. A null parameter declared as @ NonNull is passed to the method. The return value declared as @ NonNull is actually null.

Nm: The class defines the hashcode () method, but does not actually overwrite the hashCode () of the parent class Object. The class defines the tostring () method, but it does not actually overwrite the toString () of the parent class Object; it is obvious that the methods and constructors are confused; the method names are easy to confuse.

SQL: The method attempts to access the 0 index of a Prepared Statement; the method attempts to access the 0 index of a ResultSet.

UwF: all writes set the attribute to null, so that all reads are null, so that this attribute is necessary; or the attribute has never been written.

Internationalization International

When the upper or lowercase method is used for a string, an international string may be incorrectly converted.

Malicious code vulnerability Malicious attacks

If the code is public and may be maliciously attacked, the following lists the code:

FI: The finalize () of a class should be protected, not public.

MS: The attribute is a variable array; the attribute is a variable Hashtable; the attribute should be package protected.

Multithreaded correctness multi-thread correctness

The code that may cause errors during multi-threaded programming is as follows:

ESync: an empty synchronization block, which is hard to be correctly used.
MWN: the use of policy () is incorrect, which may cause an IllegalMonitorStateException or an error

Use wait ().

No: use consumer Y () instead of consumer yall (), just wake up a thread, not all waiting threads.
SC: The constructor calls Thread. start (). An error may occur when the class is inherited.

Performance problems

Code that may cause poor performance:

DM: The method calls an inefficient Boolean constructor. Instead, use Boolean. valueOf (...); Similar
Integer. toString (1) replaces new Integer (1). toString (); the method calls the inefficient float constructor and should use the static valueOf method.

SIC: If an internal class is to be referenced in a wider range, it should be declared as static.
SS: If an instance property is not read, consider declaring it as static.
UrF: if an attribute is never read, remove it from the class.
UuF: if an attribute is never used, remove it from the class.

Dodgy dangerous

Potentially dangerous code may cause errors during runtime. The following are some examples:

CI: The class is declared as final but the protected attribute is declared.
DLS: assigns a value to a local variable, but does not read the local variable. If the local variable is null, it does not read the local variable.
ICAST: the result of multiplying integer numbers is converted to a long integer number. The integer type must be converted to a long integer and then multiplied.
INT: unnecessary Integer comparison, such as X <= Integer. MAX_VALUE.
NP: a direct reference to readline () without determining whether it is null. A direct reference to a method call may return null.
REC: directly captures exceptions, which may be RuntimeException.
ST: directly modify the class variable (static attribute) from the instance method.

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.