Sunday, March 17, 2013

Manage Code Quality Using Sonar

Target audience: Beginner
Estimated reading time: 4'



Table of contents
Follow me on LinkedIn

Introduction

It is fair to say that setting up and maintaining a source code quality management is not on the top of priorities list of developers and managers alike. Despite all the good intentions, costs and/or time to market relegate the tasks of setting up a code analyzer for instances and enforcing coding best practices to the back burner. Unfortunately, those tools have gotten the reputation to be difficult to maintain and costly to license. This is not the case anymore.
  
Sonar is an open source Platform used by development teams to manage source code quality.  The main purpose of the project is to simplify code quality management.
As such, Sonar supports analysis of Java in the core, but also up to 10 different programming languages through plug-ins. The automation process associated to code quality management can be broken down along two distinct objectives:
  • Continuous integration: Build automation, static code analysis & code coverage reports
  • Continuous reviews: Best practices violations, code improvement and refactoring, stability and maintainability
Cyclomatic complexity  originally developed by Thomas McCabe, directly measures the number of linearly independent paths through a program's source code.

Readability of source code is quite often evaluated  using Fresch-Kincaid test that was originally developed for measuring the readability of academic English. The method scores the "complexity" of any document from 100 (11th grade student) to 0 domain-experts and scholars, with 50 for articles in "Time Magazine".


Dashboard

The purpose of the dashboard is to provide an overview of the static code analysis. The following report shows the analysis of the java implementation in Jena, an open source, Apache licensed, library to create and manage semantic database and RDF tuples. A devOps or manager uses Sonar to answer some basic questions before drilling down into specific problem areas.

  • Duplication: What is the percentage of redundant code that needed to be refactored, eliminated? Is the redundant code caused by poor design, legacy code?
  • Code coverage: What is the percentage of execution paths is exercised through unit test? Is poor coverage associated with violation of coding best practices.
  • Rules compliance: What are the most common violation or deviation from standards?
  • Code complexity: How difficult to maintain, modify & extend the current code base?
The dashboard can be easily upgraded using custom filters and layout.


Best practices violation

One of a "side" benefit of any static code analyzer is to force the engineering to define and maintain a set of best practices.  Sonar uses a severity ranking similar to most common defect database of  classify violation of coding standards. The following table display the severity and type of violation of best practice rule.


By default, the current version of Sonar, 3.0, contains 600 coding off-the-shelf rulesThe user can create custom rules or override existing ones using XPath expressions.
Inner Assignment
checkstyle : com.puppycrawl.tools.checkstyle.checks.coding.InnerAssignmentCheck
Checks for assignments in subexpressions, such as in String s = Integer.toString(i = 2);

Avoid Throwing Raw Exception Types

Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exception, or Error, use a subclassed exception or error instead.

Sonar allows the developers to take a snapshot of the overall quality of an application and view the evolution of quality measures across snapshots with the TimeMachine service. But this was not sufficient to provide at quick answers to the fundamental question: What changed over the past X days?
Recently, Sonar added the differential dashboard that allows developers to visualize the difference between two quality snapshots. Those quality snapshots can be assigned a version,  and purged according to a configurable policy.

Getting started

Sonar is made of 3 components:
  • Database that stores the configuration and results of quality analyses  
  • Web Server that is used to navigate the results of the analyzes and make configuration
  • Client that runs source code analyzers to compute data on projects
    Examples of static code analysis using Sonar are available on GitHub Sonar GitHub

    Installation of Sonar

    Here are the set-up to install Sonar
       1. Download the latest version of Sonar from Sonar Downloads
       2. Unzip the installation package
       3. In the directory sonar-xx/conf open and edit the Sonar property file
       4. Override the credentials

    sonar.jdbc.username: sonar  
    sonar.jdbc.password: sonar
       5. By default, Sonar is bundled with Apache Derby database
             sonar.jdbc.url: jdbc:derby://localhost:1527/sonar;create=true
             sonar.jdbc.driverClassName: org.apache.derby.jdbc.ClientDriver

       6. If you want to use your own database you need to create the database and 
           relevant tables
       7. Then specify the JDBC drivers URL and name of your database

    sonar.jdbc.url: jdbc:oracle:thin:@localhost:1521/instance-name  
    sonar.jdbc.driverClassName: oracle.jdbc.driver.OracleDriver 
    or
    sonar.jdbc.url:jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8 sonar.jdbc.driverClassName:com.mysql.jdbc.Driver

    Installation Eclipse plug-in

    Assuming Eclipse version 3.7 or later is installed...
    1. Go to Help > Install New Software... This should display the Install dialog box. 
    2. Paste the Update Site URL (http://dist.sonar-ide.codehaus.org/eclipse/) into the field Work with and press Enter. This should display the list of available plugins and components: 
    3. Check the component you wish to install. 
    4. Click Next. Eclipse will then check to see if there is any issue which would prevent a successful installation
    5. Click Finish to begin the installation process. Eclipse will then download and install the necessary components. 
    6. Once the installation process is finished, Eclipse will ask if you want to restart the IDE. It is strongly recommended that you restart the IDE.

    Integration with Jenkins

    Assuming that Jenkins continuous integration server is already installed, you need to 
    1. login into the Jenkins installation 's management screen
    2. click on Manage Plugins  menu
    3. select the Available tab. If the list of plug-ins is empty, then select Advanced tab and force to check for new updates by clicking Check now.
    4. select the check box corresponding to the Sonar plug-in for a particular language
    5. select the Install without restart option. The installation will complete

    References

    No comments:

    Post a Comment

    Note: Only a member of this blog may post a comment.