RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Small Steps Lead to Big Improvements in Java Code Quality : Page 2

Instead of setting arbitrary targets to achieve better quality Java code, use an iterative improvement strategy that delivers visible, measurable results.

Create a Coverage Report in XML
After you create the targets for instrumenting your code and running your tests, you can add incremental coverage rate checking to your build scripts. The first step is to use a cobertura-report task to create a coverage report in XML:

<cobertura-report format="xml"/>

This is an example of the report (coverage.xml) a cobertura-report task produces:

<?xml version="1.0"?>
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-02.dtd">

<coverage line-rate="0.43612334801762115" branch-rate="0.48344370860927155" version="1.8" timestamp="1181043899853">

Make sure you save this file somewhere safe (perhaps even check it into your version management system) because you will need it later.

Extract the Coverage Rate from the Report
Initially, you might be tempted to use Ant's XmlProperty task to extract the line rate directly to an Ant property. However, this approach is problematic for a couple of reasons:

  1. A quirk of Cobertura is that the line-rate values in coverage.xml are decimal fractions, while the cobertura-check task requires integer percentages.
  2. In real-life projects of significant size, coverage.xml is likely to be large in size, and any attempt to use the XmlProperty task will probably result in a Java OutOfMemoryError.

Instead, use the Ant XSLT task to extract only what you want:

<xslt in="coverage.xml" out="build/coverage.properties" style="src/xsl/coverage.xsl" />

This simple XSL template produces a properties file containing just the value that you need:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  version="1.0">
	<xsl:output method="text" omit-xml-declaration="yes"/>
	<xsl:template match="coverage">
		<xsl:value-of select="floor(@line-rate*100)"/>

Note the method floor(@line-rate*100), which converts the line rate to a percentage and rounds it down to the nearest integer. The result is a coverage.properties file containing just one line:


In contrast to coverage.xml, which you should save between builds, coverage.properties is just an intermediate stage that you can clean up after the build.

You can now use Ant's property task to read the value from coverage.properties into an Ant property named total.line-rate:

<property file="build/coverage.properties" />

Finally, you can replace the "80" in the original cobertura-check task with the newly set Ant property:

<cobertura-check totallinerate="${total.line-rate}"/>

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date