Monday, May 3, 2010

Static code analysis prevents entire classes of errors

- Nathan Jakubiak, Software Development Manager

Recently we found a bug in our software that resulted in a null variable being dereferenced and throwing an exception. We have static analysis rules enabled, so we wondered why they did not catch the problem.

We discovered that there was a rule in Jtest that could have found the problem - "Avoid using "private" fields which are never given a meaningful value" - and flag if those variables ever got dereferenced. So we turned the rule on. This rule was in a Jtest category called Possible Bugs, so we combed through that category looking for other Serverity 1 rules that we possibly should have turned on.

We found and enabled the high severity rule "Do not call 'equals()' methods that always return false", which turned up a number of bugs!

In our code we have calls that look like Logger.getlogger().error("some error message"). In some cases a developer had accidentally used the equals() method insead of the error() method. The resulting code compiled fine, but did not do the logging that was intended. Jtest found this problem since the equals() method was passing a String to the equals() method of a Logger object - and this would always return false.

In this process we also turned on the rule "Avoid calling 'equals()' with same object", which also found us a bug! This bug was in the equals() method of an object called XMLAssertionTool, and could cause the method to consider two instances of XMLAssertionTool equal even if their message field had a different value, as shown below:


public boolean equals(Object obj) {
     if (!(obj instanceof XMLAssertionTool)) {
          return false;
     }
     XMLAssertionTool other = (XMLAssertionTool)obj;
     return assertions.equals(other.assertions) &&
          message.equals(message) && toolEquals(obj);
     // The problem is: "message.equals(message)"
}


Learn how Parasoft helps developers do static analysis, and more.

1 comment:

  1. Static analysis tools comparison are an important way of checking for coding style violations. They are particularly effective at finding language use that is ambiguous or dangerous.
    secdevops

    ReplyDelete