Wednesday, May 26, 2010

Static analysis finds errors functional tests miss

- Rami Jaamour, Software Development Manager

Recently I wrote some SOAtest code which relates to Parasoft SOAtest's Stub Server 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(...);
          ...
     }
}


Functionally speaking, everything seems fine when you test it. However, in reality this code has not been using the right connection type, which is a defect that could manifest itself in certain heterogeneous contexts that are different from our test environments. I cannot test my functionality under all possible environmental configurations, so this problem could have gone unnoticed, but luckily 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" is just awesome! This rule detects "private" fields which are used but which are 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 none null value, or if the code has a collection object (array, vector, etc.) that is instantiated but items are never added to it. In my case the rule helped me fix my code by initializing my provider field in the constructor and prevent a bug from creeping into the release:


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(...);
          ...
     }
}


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

No comments:

Post a Comment