Book Image

Sonar Code Quality Testing Essentials

By : Charalampos S Arapidis
Book Image

Sonar Code Quality Testing Essentials

By: Charalampos S Arapidis

Overview of this book

Sonar is an open source platform used by development teams to manage source code quality. Sonar has been developed with this main objective in mind: make code quality management accessible to everyone with minimal effort. As such, Sonar provides code analyzers, reporting tools, manual reviews, defect-hunting modules, and TimeMachine as core functionalities. It also comes with a plugin mechanism enabling the community to extend the functionality, making Sonar the one-stop-shop for source code quality by addressing not only the developer's requirements, but also the manager's needs.The "Sonar Code Quality Testing Essentials" book will help you understand the different factors that define code quality and how to improve your own or your team's code using Sonar. You will learn to use Sonar effectively and explore the quality of your source code in the following axes: Coding Standards Documentation and Comments Potential Bugs and Defects Unit Testing Coverage Design and Complexity Through practical examples, you will customize Sonar components and widgets to identify areas where your source code is lacking. The book goes down to proposing good practices and common solutions that you can put to use to improve such code.You will start with installing and setting up a Sonar server and performing your first project analysis. Then you will go through the process of creating a custom and balanced quality profile exploring all Sonar components through practical examples. After reading the book, you will be able to analyze any project using Sonar and know how to read and evaluate quality metrics.Hunting potential bugs and eliminating complexity are the hottest topics regarding code quality. The book will guide you through the process of finding such problematic areas, leveraging and customizing the most appropriate components. Knowing the best tool for each task is essential. While you improve code and design through the book, you will notice that metrics go high and alerts turn green. You will use the Time Machine and the Timeline to examine how your changes affected the quality."Sonar Code Quality Testing Essentials" will enable you to perform custom quality analysis on any Java project and quickly gain insight on even large code bases, as well as provide possible solutions to code defects and complexity matters.
Table of Contents (18 chapters)
Sonar Code Quality Testing Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Sonar Metrics Index

Features of Sonar


The Sonar platform comes with a vast array of components in order to provide insightful and accurate information. Moreover, its flexible architecture allows functionality to be added on demand via a plugin system.

Let's take a closer look at the features the core platform has to offer:

Overview of all projects

With Sonar's project dashboard, you gain quick access to and insight about all your projects through a comprehensive dashboard. The dashboard presents vital quality metrics in an efficient way, highlights sections which require your attention, and finally includes common interface practicalities, such as sorting, adding, or removing columns to make browsing easier. The majority of the user interface is implemented in AJAX and the transitions between the different views and drilldowns are quick and smooth. Likewise, the components of the platform from simple to more complex ones are very responsive and react in a timely fashion to your actions.

The dashboard is fully customizable, and you can select which metric columns each view contains and reorder them as you like. The ability to internationalize the platform is a huge plus allowing you to present a total solution covering every aspect, from pleasant and practical interface to language settings. Generally speaking, language friendliness is very much welcomed if you intend to provide a Sonar instance to a less-technical audience.

If you want to take look at the Sonar dashboard in full swing, point your browser at Nemo, a Sonar demo instance by SonarSource S.A. hosting the platform's own source code among other well-known open source projects at http://nemo.sonarsource.org.

Coding rules

More than 600 rules are incorporated into Sonar, performing simple checks to complex calculations. Rules can be fully parameterized to meet different development needs, and if this is not enough, with a little help from the lively community, you can even implement your own, covering every possible need.

The strictest Sonar profile includes about 720 rules, but probably you won't ever need to activate it. It is not even suggested to use all of them at all. The objective is to provide as many coding rules as possible and let the developer make choices accordingly, assigning them to custom profiles for projects. Obviously, there is the ability to host multiple different profiles with specific sets of rules and further assign these profiles to different projects for maximum flexibility.

Standard software metrics

Metrics are necessary to form objective and reliable opinion on any piece of software. Like in every science or process, metrics are essential to measure and reproduce behavior and functionality, and help evaluate/compare source code, establishing a common ground among different pieces of software. In other words, metrics form a common denominator for all software and they have become an integral part of the development process.

Note

Not a magic bullet

Sonar is not a magic bullet. A solid development process, creativity, dedication, and practical design are still some of the necessary virtues to create a successful and quality product. Writing code for the sake of metrics is basically cheating. Tricking the system to produce desirable results, disconnected from the functional requirements, is as you understand under-productive. Such a bad practice only detracts from the final product instead of improving it.

One use for software metrics, which does not have to do directly with quality is that they can also provide insight and deeper knowledge about the source code, revealing potential pitfalls, and providing a safe guideline for new developers to follow. Sonar includes all classical metrics related to software development, some of them being:

  • Lines of code

  • Documented API

  • Cyclomatic complexity

  • Test coverage

  • Duplicated code

Unit tests

If you have at least a couple of development years under your belt at some time or another, you have probably wondered how you could ever manage without writing any tests for your code. Untested software results in an unstable product, not working as expected. Experience shows that the first thing the end user does with an untested feature ends up to be unexpected and never taken into consideration during development. Random input, experimenting, or using the feature/component for something other than what it was designed for, are all viable and very real cases. While clients demand dynamic help systems and comprehensive manuals, they never ever read them, expecting the software to meet their expectations one way or another.

Software testing verifies that a feature will work as expected and meets design requirements. However, writing tests for the sake of testing only to cheat the metrics, covering low-risk code, and leaving out crucial areas, is pointless. This kind of testing, while it consumes time and resources, adds nothing to the final quality of your product.

Sonar identifies high-risk software pieces and locates untested code not only at line, but even at branch level, taking into consideration all possible outcomes of a conditional operation. Additionally, Sonar provides useful statistics concerning test successes and total duration.

Drill down to source code

Knowing where quality suffers and what aspects of your software need to be strengthened is one thing, specifically locating these problematic areas is another. Sonar features smart components as the metrics radiator that in combination with the dashboard allow you to drill down effortlessly to your source code reaching classes that require attention quickly. It may sound like a complex investigative task or an alternative search tool for your source code but this is not the case.

Drill down is a standard professional method used to browse code. You set a focal point, undocumented code for example, and move downwards from summary information to more detailed data, subsequently exploring modules, packages, and classes.

Time Machine

Sonar stores all analysis results in a database, preserving historical data for future reference and comparison, enabling you to track the evolution of your code. At any time you can check out a past version of your codebase from the repository and add it to the project's time line for comparison. Examining a data point in isolation can enlighten your team about the state of the code in the given time frame, but the information accumulated by the historical data proves to be invaluable in the long run, helping to determine the best approach for the health of your project.

You can examine the progress of your code using one of the three different components available: the Time Machine, the Motion Chart, and the Timeline. Each component can be dynamically customized to access historical data on all metrics supported. The Motion Chart, the fanciest of the components, features an animated bubble chart tracking metrics in four different dimensions: the X and Y axes, plus the color and size of the bubbles.

Maven ready

Maven is a build automation tool like Ant, streamlining the steps of the build process in software development. Checking out code, compiling, generating documentation and reports, running tests, producing artifacts, and finally deploying them, are some of the goals supported by Maven and implemented via plugins. Different profiles described in XML configuration files dictate the execution steps that take place during the build process while providing configuration details.

The Sonar platform takes advantage of the Maven goal-oriented philosophy, simplifying configuration. All you have to do is add the Sonar Maven Plugin into your project to get support for Sonar-oriented goals. The only requirement is to have the Sonar server up whenever the goal is executed. Basically, the setup requires zero or minimal configuration if you are familiar with Maven.

User friendly

Much thought and work has been put into the platform's user interface in regards to both appearance and behavior. The clean interface is mostly self-explanatory but if you have any queries or feel like clarifying some things more, there is plenty of documentation and media available within the Sonar community covering many topics, from traditional getting started wikis to screencasts exploring advanced Sonar features. It is important to note here the web nature of the user interface, accessible straight from your browser.

Unified components

Sonar introduces a new paradigm on measuring quality without trying to reinvent the wheel in the field of metrics and rules. While it features its own implemented set of rules, under the hood most work is handled by familiar and long-trusted tools. Sonar unifies these tools, leveraging existing functionality, collecting output, and finally refining the results to follow suit with the platform's objective.

As SonarSource puts it:

Sonar can transparently orchestrate all those components for you.

Obviously, the procedure of running these tools manually in sequence to produce raw values and statistics is now rendered obsolete, since Sonar automatically streams the whole process in one combined analysis step.

Security measures

Sonar features a standard role-based authentication system allowing you to secure your instance, create as many users as required, and assign them to groups. A user can belong to more than one group, while access to the various Sonar services and functionality can be fine-grained by assigning appropriate roles.

Two groups have a special status in Sonar:

  • Anyone: is a group that exists in the system but cannot be managed. Every user belongs to this group.

  • Sonar-users: is the default group to which every user exists. It is not possible to configure the name of this group.

Of the four roles available in Sonar, one is global, referring to the instance, and the three others are attached to projects:

  • Global Administrators: Can perform all administration functions for the instance: global configuration, personalization of the Time Machine, and the home page

  • Project Administrators: Can perform administration functions for a project by accessing its settings

  • Project Users: Can navigate through every service of a project, except viewing source code and settings

  • Project Code Viewers: Can view the source code of a project

If a global security system exists within your environment, such as Atlassian Crowd SSO, LDAP, or Microsoft Active Directory, you can delegate all Sonar authentication function to these systems using the appropriate plugins.

Extensible plugin system

The Sonar platform is extensible via a plugin system. More functionality can be added using plugins, either open source or commercial. A dedicated repository located at http://sonar-plugins.codehaus.org/ hosts the Sonar plugin library. From there, you can choose and download the plugins you require for your Sonar instance and read documentation and installation instructions specifically written for each one separately. Plugins enable Sonar to measure more programming languages, add more metrics and rules, and integrate the platform with third-party systems such as LDAP or Continuous Integration build servers.

Some of the more interesting plugins and a brief description of what they do are shown in the following list:

  • Additional languages:

    • PHP: Analysis using PHP Unit, PHP Depend, PHP MD, and SQLI CodeSniffer

    • Groovy

    • JavaScript

    • C, C#

    • Web: currently supports analysis for JSF and JSP pages.

  • Additional metrics:

    • Build stability: Reports on stability of project build using Continuous Integration engine data

    • Rules meter: Gives information on the level of activation of projects' quality profiles

    • Sonargraph: Provides architecture governance features accompanied by metrics about cyclic dependencies and other structural aspects

    • Useless code: Reports on the number of lines that can be reduced in an application

  • Visualization/Reporting:

    • PDF Report: Generates a PDF report with analysis results

    • Timeline: Displays measures history using a Google Timeline Chart to replay the past

  • Governance:

    • Quality Index: Calculates a global Quality Index based on coding rules, style, complexity, and unit-testing coverage

    • Technical debt: Calculates the technical debt on every component with breakdown by duplications, documentation, coverage, and complexity

    • SQALE—Quality Model (Commercial): An implementation of the SQALE Methodology

  • Integration:

    • Hudson/Jenkins and Bamboo: Enables to configure and launch Sonar analysis from Hudson or Jenkins continuous integration engines

    • Crowd and LDAP: Enables delegation of Sonar authentication to Atlassian Crowd and to LDAP or Microsoft Active Directory respectively

    • Switch off violations: Excludes some violations in a fine-grained way

  • IDE:

    • Eclipse: Accesses information gathered by Sonar directly in Eclipse and fixes them on the spot

  • Localization:

    • Supports French and Spanish languages