As a requirement of our current project, we wanted to establish a minimum criteria of code quality ahead of formal code inspections. No point in wasting valuable brain capacity at spotting simple problems such as using “==” instead of “equals” and so on.
Static code analysis is a good starting point, though it can be a bit intransigent about false-positives, where the developer had good cause to write code in a way that the rule developer could not have anticipated.
Being that our main development tool is Eclipse, this was the one criteria that made me give up on the excellent FindBugs, in that there was no way to mark up the source code to tell FindBugs to ignore the problem in future scans.
Enter the Eclipse built-in code analysis, which not only allows scanning source code, but also has a simple way of marking false-positives inside the source code using a Java comment, so that further scans will not flag the problem again.
Sharing a rule base
The first step in sharing a rule base is to create one, which can be done from the “Run –> Analysis…” menu.
Set the “Scope” to “Analyze selected projects”, without actually checking any project box. This will allow you to right-click any project and then run the analysis only on the selected project.
Under “Rules”, pick the ones you consider the most important. It took me a couple of scans on pre-existing code to weed out the faulty ones (there are a few) and the overly conservative ones. Once I was satisfied, I clicked on the “Export…” button to save it to a file I could share with my colleagues.
Importing a rule base
Starting from the “Run –> Analysis…” menu again, click on the “New launch configuration” button, give it a name. Again, set the “Scope” to “Analyze selected projects”, without actually checking any project box.
In the “Rules” tab, click on the “Import…” button and select the “.dat” file exported in the previous step, which is stored in a location shared with the entire team.
Scanning the code
Right-click a Java project and select “Analysis –> [Name of your launch configuration]”. In a few seconds, the results will be displayed in the “Analysis Results” view.
Right-clicking any of the individual results shows a menu with options for a “Quick Fix” (available for some rules) or the selection of “Ignore Result”. The latter option will add a Java comment next to the flagged line of code, instructing the analyzer to not flag the problem in future scans.