findbugs for static code checking

The static check in white box test is generally to check the coding standard, specification and error list. Coding specifications often the team will set some specifications according to their own experience and style. Now many IDE tools will remind whether it conforms to the code style in real time when editing the code. The error list is generally a potential bug in the code. Although there is no syntax error in a certain code writing method, there may be errors, such as thread deadlock. These are what the error list should check. Operational mode of static inspection:

  • Code walk through
    Programmers can extract code for walk through at regular intervals.
    During the walkthrough, these experiences are summarized into a list according to the summary report as the basis for the next code walkthrough.
    This method is characterized by manual, multi person discussion and simple operation, but the efficiency will be relatively low.
  • Code scanning
    Use software to scan our code to find potential problems. Now there are many commercial tools that can scan, such as Parasoft JTest, Software Analyzer, pclint and other tools. Different tools often target different languages. Of course, there are many open source tools. Here, findbugs is mainly recommended for java. Findbugs can run in multiple environments, and can also write its own detector with perfect functions. We can usually collect our own or other people's development experience and make it into a detector to improve the detection system of findbugs. Software scanning is characterized by machine scanning and high efficiency, but it is not flexible enough.

Comparison of Java static inspection tools

reference resources:

toolobjectiveInspection items
FindBugs check classBased on the concept of Bug Patterns, find potential bugs in javabytecode (. class file)Mainly check the bug patterns in bytecode, such as null point null pointer check, unreasonable closing of resources, wrong judgment of the same string (= =, not equals), etc
PMD check source fileCheck for potential problems in Java source filesIt mainly includes: empty try/catch/finally/switch statement block; Unused local variables, parameters and private methods; Empty if/while statement; Overly complex expressions, such as unnecessary if statements; Complex class
CheckStyle checks the format of the source fileCheck whether the Java source file conforms to the code specificationIt mainly includes: Javadoc comments; Naming conventions; Redundant and useless Imports;Size measurement, such as too long method; Missing required Whitespace; Duplicate code

1, Introduction to findbugs

Findbugs is a static analysis tool that examines classes or JAR files and compares bytecode with a set of defect patterns to find possible problems. Findbugs comes with its own detectors, including more than 60 bad practices, more than 80 corrections, 1 Internationalization, 12 Malicious code vulnerability, 27 multithreaded corrections, 23 Performance and 43 doggy. We can also configure our own check rules (what checks to do and what not to do) or implement our own unique check rules (users need to inherit its interface and write their own check classes to customize a specific bug mode, which belongs to advanced skills).

2, Method of use

2.1 Ant tools

Ant is a good Java automatic execution tool.

Findbugs officially provides Ant's findbugs operation method. We can use such a build XML file to use findbugs.

<project name="Project name" default="all">
<property name="findbugs.home" value="findbugs Decompression path" />
              <path id="findbugs.path">
                  <fileset dir="findbugs Decompression path">
                        <include name="**/*.jar" />
              <taskdef name="findbugs"
                   classpathref="findbugs.path" />
              <!--  definition findbugs of home,findbugs of task To use  -->
              <target name="findbugs">
                   <findbugs home="${findbugs.home}"
                        output="xml:withMessages" outputFile="Generated files">
                        <!--  Above definition findbugs Class path to find  -->
                        <auxClasspath path="${findbugs.home}/lib/findbugs-ant.jar" />
                            <fileset dir="lib"
                            includes="*.jar" />
                        <sourcePath path="Source file path" />
                        <class location="Generate classpath" />

After setting the - f.Ant environment, use the - build command xml, or run build.xml directly in Eclipse xml file. After running, an xml file is generated. If you want to view the results of findbugs in HTML format, you can set the output attribute to HTML. In this way, you can view the results of findbugs through HTML.

2.2. Findbugs Eclipse Plug-in

The Findbugs plug-in of Eclipse can integrate Findbugs into Eclipse for use.

2.2.1 installation method of Eclipse Plug-in of Findbugs

  1. Online installation

Installation address:

  1. Offline installation

Download the Findbugs plug-in, put it in the plugin folder under Eclipse, and then restart Eclipse

2.2.2 use of Eclipse Plug-in of Findbugs

After installing the Findbugs plug-in. Right click the item you want to check and select [Find Bugs] - [Find Bugs] to check.

To see which bugs are detected by Findbugs, you can select Windows menu - > show view - > Bug explorer to open the Bug Explorer panel.

If you want to view the detailed information of a Bug, you can select Windows menu - > open perspective, and then select FindBugs to open the Properties panel of FindBugs, where you can see the most detailed Bug information.

2.2.3 relevant settings of configurable options

1. Run FindBugs Automatically switch
 When this option is selected, FindBugs Will be revised after you Java Class runs automatically, if you set Eclipse After the auto compile switch, when you finish modifying Java File saving, FindBugs It will run and display the corresponding information.
When this item is not selected, you can only run it by yourself every time you need it FindBugs To check your code.

2. Minimum priority to report Select item
 This option allows you to choose which level of information to display. There are Low,Medium,High Three options can be selected, which is very similar to Log4J Level setting. For example:
You chose High Option, then only yes High Level prompt information will be displayed.
You chose Medium Option, then only yes Medium and High Level prompt information will be displayed.
You chose Low Select the item, and all levels of prompt information will be displayed.

3. Enable bug categories Select item
 Here are some displays Bug Selection of classification:
Correctness On relevant aspects of code correctness
Performance On code performance related aspects
Internationalization About code internationalization
Multithreaded correctness On the correctness of code multithreading
Style About code style
Malicious code vulnerability On malicious code related aspects
 For example, if you put Style If the check box is removed and it is not selected, then Style The warning information related to classification will not be displayed. Others are similar.

4. Select bug patterns to check for Select item
 Here you can select the relevant to be checked Bug Pattern entry

Can from Bug codes,Detector name,Detector description You can select or remove the corresponding inspection conditions according to your needs.

3, FindBugs error type description

Bad practice Bad practices are listed below:
	HE: In class equals()And hashCode()Not defined at the same time, or the wrong object is used hashCode()or equals(). 
	SQL: Statement of execute Method calls a non constant number of strings; or Prepared Statement Is generated by a non constant string.
	DE:  Methods terminate or do not handle exceptions. In general, exceptions should be handled or reported, or thrown by methods.

Correctness General correctness problems and codes that may lead to errors are listed below:
	NP:  Null pointer is referenced; In the exception path of the method, the null pointer is referenced; Method does not check whether the parameter is valid null;null Values are generated and referenced; null The value is generated and referenced in the exception path of the method; Pass a declaration to the method@NonNull of null Parameters; The return value of the method is declared as@NonNull the truth is that null. 
	Nm:  Class defines hashcode()Method, but does not actually override the parent class Object of hashCode();Class defines tostring()Method, but does not actually override the parent class Object of toString();Obviously, the method is confused with the constructor; Method names are confusing.
	SQL: Method attempts to access a Prepared Statement 0 index of; Method attempts to access a ResultSet Index of 0.
	UwF: be-all write Set the attribute to null,So all reads are null,Whether this attribute is necessary; Or attribute has never been write. 

Internationalization Internationalization, when used with strings upper or lowercase Method. If it is an international string, it may be improperly converted.

Malicious code vulnerability Possible malicious attacks. If the code is public, the code that may be attacked by malicious attacks is listed below:
	FI:  Of a class finalize()Should be protected,instead of public of
	MS: Property is a variable array; Properties are mutable Hashtable;Attribute should be package protected of

Multithreaded correctness Correctness of multithreading. The codes that may cause errors during multithreading programming are listed below:
	ESync: Empty synchronization blocks are difficult to use correctly.
	MWN: Wrong use notify(),May cause IllegalMonitorStateException Abnormal; Or wrong use wait(). 
	No:  use notify()instead of notifyAll(),Just wake up one thread, not all waiting threads.
	SC:  Constructor called Thread.start(),When this class is inherited, it may cause errors.

Performance There are several performance problems that may lead to the following code:
	DM: Method called an inefficient Boolean Instead of using a constructor Boolean.valueOf(...);Use similar Integer.toString(1) replace new Integer(1).toString();Method called an inefficient float The constructor should be static valueOf method.
	SIC: If an inner class wants to be referenced more widely, it should be declared as static. 
	SS:  If an instance property is not read, consider declaring as static. 
	UrF: If an attribute has never been read,Consider removing from the class.
	UuF: If an attribute is never used, consider removing it from the class.

Dodgy Dangerous and potentially dangerous codes may cause errors during operation. The following are listed:
	CI:  Class declared as final But the statement protected Properties of.
	DLS: Assign a value to a local variable, but the local variable is not read; The local variable is assigned to null,The local variable was not read.
	ICAST:  The multiplication result of integer numbers is transformed into long integer numbers. Integers should be transformed into long integer numbers first and then multiplied.
	INT: Unnecessary integer number comparison, such as X <= Integer.MAX_VALUE. 
	NP:  yes readline()Without judging whether or not null;A direct reference to a method call, which may return null. 
	REC: Direct capture Exception,In fact, it may be RuntimeException. 
	ST:  Modify class variables directly from the instance method, i.e static Properties.

4, Reference documents






Added by Instigate on Mon, 14 Feb 2022 04:52:36 +0200