vendredi 11 octobre 2013

Remove dead code from your application

The problem:
Code coverage estimation is mostly based on Automated Unit Testing and software like JUnit. Doing like this is okay to increase youy coverage rate, but sometimes has a pernicious effect. Because it does not guarantee that the code you cover is really necessary to your application, and so you may have some portions of code covered but unrelevant for the actual application business.

Unecessary code detected with UCDetector:
In order to avoid this unecessary code, you have several alternatives. The first is to use the excellent eclipse plugin UCDetector (standing for Unecessary Code Detector) downloadable at http://www.ucdetector.org/. This detects in a friendly way the code that is not referenced elsewhere in the project.

This plugin must be applied to relevant package for application business. Indeed,  service packages and dao packages are good candidates. The result comes in the markers tabs of eclipse. You can then decide weither or not, those method shall be kept or not. 



Unecessary code detected with Tomcat and code coverage:
The below method can only apply to the low layer in a webapp, because you cannot check the code accessed throught JSP. For an in deep investigation of the actual code used, you may use cobertura and tomcat together.

Supposing you have a maven project. Here is the way to do it.
First, build your package :
- mvn package

The project is built in the target/myproject.war archive.

- mvn cobertura:instrument

This creates a folder named
- target\generated-classes\cobertura containing the instrumented classes.

This also creates a file named :

- target\cobertura.ser this files is a database storing the coverage information.

We have to build an instrumented war.

- Unzip the myproject.war file in the folder myproject
- Copy the cobertura.jar file in the myproject/WEB-INF/lib folder
- Replace the classes in folder myproject/WEB-INF/classes by the one produced in target\generated-classes\cobertura

Now it is time to prepare your tomcat:
Copy the cobertura.ser file in the folder where you will launch tomcat. If you are lauching tomcat through the windows explorer,  this folder is the /bin/ directory. If your are lucnhing it through a console, the folder is the current working directory.

Now you can run your tomcat.

Finally produce your report using the command

cobertura-report.bat --datafile ./cobertura.ser --destination ../report --format html ../sources/

Specials if you have your project distibuted in several modules^, you may first merge your cobertura information into a single file before launching tomcat :

cobertura-merge.bat --datafile target/cobertura_final.ser ../myproject-service/target/cobertura/cobertura.ser ../myproject-webapp/target/cobertura/cobertura.ser

Aucun commentaire: