Improving Code Quality
In this article I discuss a static analysis tool that finds defects in Java programs. Static analysis tools can find real bugs and real issues in your code. You can effectively incorporate static analysis into your software development process.
FindBugs
FindBugs is an open source static analysis tool that analyzes Java class files, looking for programming defects. The analysis engine reports nearly 300 different bug patterns. Each bug pattern is grouped into a category (e.g., correctness, bad practice, performance and internationalization), and each report of a bug pattern is assigned a priority, high, medium or low.
Let’s start with some of the bug categories that I find very interesting
Correctness
The code seems to be clearly doing something the developer did not intend
Infinite recursive loop
public String resultFound() {
return this.resultFound();
}Null Pointer Bugs
FindBug look for the statement that when execute will surely produce Null Pointer Exceptio. Some examples are
if (str != null || str.length > 0)
if (str == null || str.equals(""))
if (obj != null)
//code to be execute
obj.doSomeThing();
The below code is a relatively simply bug. If the test null == elt evaluates to false, we are guaranteed to get a null pointer exception when we dereference obj by invoking the equals method on it.
while(it.hasNext()) {
Object elt = it.next();
if((null == obj && null == elt)
|| obj.equals(elt)) {
count++;
}
Redundant Check for Null
We usually do such mistake. A value is checked here to see whether it is null, but this value can't be null because it was previously dereferenced and if it were null a null pointer exception would have occurred at the earlier dereference.
if(screen instanceof BasicScreen) {
BasicScreen basicScreen = (BasicScreen) screen;
BusinessComponent businessComponent = basicScreen.getBusinessComponent();
if(basicScreen!=null) {
dataBean = (UnderwriterPriority)businessComponent.getDataBean();
}
}Above Figure shows the NULL Check of basic screen at line 4 of value previously dereference at line3.
Method whose return value should not ignore
We all know string is immutable object. So ignoring the return value of the method would consider as bug.
String name = "Muhammad";
name.toUpper();
if (name.equals("MUHAMMAD"))
Suspicious equal() comparision
The method calls equals(Object) on two references of different class types with no common subclasses
Integer accountTypeValue = dataBean.getAccount_type_code();
if (accountTypeValue != null && !"".equals(accountTypeValue))
result = (accountTypeValue).intValue();
According to the contract of equals(), objects of different classes should always compare as unequal; Therefore equal comparision in line 2 always return false.
Bad Practice
Violations of recommended and essential coding practice. Examples include hash code and equals problems, cloneable idiom, dropped exceptions, serializable problems, and misuse of finalize.
Hash equals mismatch
Class defines equals() and uses Object.hashCode(). The class overrides equals(Object), but does not override hashCode(), and inherits the implementation of hashCode() from java.lang.Object (which returns the identity hash code, an arbitrary value assigned to the object by the VM). Therefore, the class is very likely to violate the invariant that equal objects must have equal hashcodes.
Ignore serialVersionUID
Class implementing serializable interface but forget to declare an explicit serial version UID.
Ignore Exception return values
Noncompliant Code ExampleThe following calls to java.io.File methods are non compliant because the program does not check the return
value, and hence does not know whether the operation succeeded.
void do_operation() {
File directory, file;
// fetch directory
directory.mkdir();
// do some operations on file and directory
file.delete();
}Compliant SolutionA compliant solution provides error handling to recover from an unsuccessful operation. This can be as simple as throwing an exception
void do_operation() throws FileNotFoundException {
File directory, file;
// fetch directory
if (( !directory.isDirectory()) && ( !directory.mkdir()) ) {
// recover from error or throw an exception
throw new FileNotFoundException("Unable to create directory " + directory );
}
// do some operations on file and directory
if ( !file.delete()) {
// recover from error or throw an exception
throw new FileNotFoundException("Failed to delete file " + file );
}
}Dodgy
Code that is confusing, anomalous, or written in a way that leads itself to errors. Examples include dead local stores, switch fall through, unconfirmed casts, and redundant null check of value known to be null.
instanceof will always return true
The instanceof test will always return true (unless the value being tested is null)
NodeList nodeList = root.getElementsByTagName("node");
int nodeListLength = nodeList.getLength();
for (int i = 0; i < nodeListLength; i++) {
Node node = nodeList.item(i);
if (node instanceof Node && node.getParentNode() == root) {
//do code
}
}
Class doesn't override equals in superclass
This class extends a class that defines an equals method and adds fields, but doesn't define an equals method itself. Thus, equality on instances of this class will ignore the identity of the subclass and the added fields.
Check for oddness that won't work for negative numbers
The code uses x % 2 == 1 to check to see if a value is odd, but this won't work for negative numbers (e.g., (-5) % 2 == -1). If this code is intending to check for oddness, consider using x & 1 == 1, or x % 2 != 0.
When should such defects be fixed?
Since these defects doesn’t cause the program to significantly misbehave, therefore the question is should these types of defect be fixed? The main arguments to fix these defects is that they require some good resources that could be better applied elsewhere, and that there is a chance that the attempt to fix the defect will introduce another, more serious bug that does significantly impact the behavior of the application. The primary argument for fixing such defects is that it makes the code easier to understand and maintain, and less likely to break in the face of future modifications or uses.
Resources
Download the latest version of FindBugs.
Visit the blog.
Using the FindBugs Ant task.
Using the FindBugs Eclipse plugin.
- Login or register to post comments
- 6360 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)















Comments
mgira replied on Mon, 2009/06/08 - 2:39am
I'm not sure if always adding a serialVersionUID to a serialisable class is a best practise.
After all, the decision to serialise/desirialise between different versions of the class has to be made explicit and not implizit for all serialisable classes, since under normal circumstances this is not what you want and it will lead to undifined behaviour if the classes haven't been designed that way.
m_muhammadali replied on Mon, 2009/06/08 - 12:09pm
Mike P(Okidoky) replied on Mon, 2009/06/08 - 1:22pm
orezavi replied on Mon, 2009/06/08 - 11:58pm
andy_cis replied on Tue, 2009/06/09 - 9:47am
I second the last paragraph. Static analysis results tend to have results that can range from: false positives (where the bug report is just wrong) to low to high priority defects. Some tools are noiser than others but most do a good job of pointing out issues that should be fixed. It also can find those occasional killer bugs with good regularity. However, in my experience at Code Integrity Solutions, the day-to-day bug reports fit in the "yeah, I should fix it but it's not important right now" category. Not surprisingly, in any software development organization's bug database there are often a large number of similarly categorized defects. You're going to have a few bugs that fit in the high priority range and a large number in the medium and low priority. The difference with static analysis though is that you are getting these bug reports as you are developing and so it is much more efficient to clean these out as you are developing than looking at a bug report and starting from scratch to debug it. The natural tendency is to ignore the reports coming from the static analysis tool. A good practice is to make sure everything is clean before checking into the main line (that means every defect, at minimum, should be looked at and categorized).
tomlo replied on Wed, 2009/06/10 - 2:09am
Walter Bogaardt replied on Wed, 2009/06/10 - 5:37pm
This is a good idea, but it seems predicated on you specifically run Findbugs on your code base, or add to ant task. It should be integrated into your build environment and looked. In fact if you want true enforcement you would use it to "break" your CI builds to enforce compliance. There is arguments to be made about being a maniac about following coding standards and allowing some level of non-compliant code in your applications.
m_muhammadali replied on Thu, 2009/06/11 - 5:17am
in response to: wb110497
m_muhammadali replied on Thu, 2009/06/11 - 5:18am
in response to: wb110497
tiffanyjewelry replied on Fri, 2009/06/26 - 3:12am
Marlet replied on Thu, 2009/07/30 - 7:37pm
links replied on Tue, 2009/08/25 - 1:49am