Static Analysis Finds Software Defects that Functional Tests Miss
Posted on Thu, Dec 02, 2010

- Rami Jaamour, Software Development Manager
Recently I wrote some code that relates to Parasoft SOAtest's behavior virtualization functionality.
One of the private fields in the class I wrote was a "provider" field, which can be used to manufacture WebSphere, Tibco, or other vendor-specific connections. That "provider" field was never initialized, so the code would take the route of using a generic connection.
public class JMSReporter {
...
private JMSProvider provider = null;
private Connection connection;
public JMSReporter(ReportingConfiguration reportingConfig) {
init();
}
public init() {
...
if (provider == null) {
connectionFactory = getGenericConnectionFactory(...);
} else {
// this code never executes
connectionFactory = provider.getConnectionFactory(...);
}
connection = connectionFactory.createConnection(...);
...
}
}
This Defect Could Slip Through Functional Testing
Functionally speaking, everything seems fine when you test it. However, in reality, this code is not using the correct connection type.
This is a defect that could manifest itself in certain heterogeneous contexts that are different from our test environments. Since it's not feasible to test this functionality under every possible environmental configuration, this problem could have gone unnoticed during testing.
Static Analysis to the Rescue
Fortunately, a static analysis rule came to the rescue and helped me expose the bug in my code. The Parasoft Jtest rule "Avoid using 'private' fields which are never given a meaningful value" saved me here.
This rule detects "private" fields that are used, but never set to a meaningful value. For example, the code might have null checks whenever the field is used but the field is never set to a non-null value, or if the code has a collection object (array, vector, etc.) that is instantiated but items are never added to it.
Eliminating the Defect
In my case, the rule helped me fix my code by initializing my provider field in the constructor.
public class JMSReporter {
...
private JMSProvider provider = null;
private Connection connection;
public JMSReporter(ReportingConfiguration reportingConfig) {
provider = reportingConfig.getProvider
init();
}
public init() {
...
if (provider == null) {
connectionFactory = getGenericConnectionFactory(...);
} else {
// this code never executes
connectionFactory = provider.getConnectionFactory(...);
}
connection = connectionFactory.createConnection(...);
...
}
}
***
Photo Credit: AZRainman
Want to learn more about static analysis—static code analysis, data flow static analyis, and code metrics analysis? Get our Static Analysis Best Practices Guide: a 6 page guide to why, when, and how to apply these static analysis techniques.