~ Static Code Analysis For Java Using Eclipse» By Joren on Thursday 03 June 2010
This post is about the tools I use to keep the source code of Tarsos reasonably clean, consistent and readable. Static code analysis can be of great help if you want to maintain strict coding standards and follow language idioms. Some of the patterns they can detect for you:
- Dead code – unused variables, parameters, methods
- Suboptimal code – wasteful resource usage
- Overcomplicated expressions – unnecessary if statements, for loops that could be while loops
- Duplicate code – copied/pasted code is a code smell.
- Formatting inconsistencies, e.g. variable modifier order
And even more subtle, but equally important:
- Resource management: is a resource handled (closed) correctly on all possible code paths?
- Abstraction level: is it needed to expose the concrete type of an object or could an (abstract) supertype or even an interface be used instead?
In a previous life I used .NET and the static code analysis tools FxCop & StyleCop. FxCop operates on bytecode (or intermediate language in .NET parlance) level, StyleCop analyses the source code itself. Tarsos uses JAVA so I looked for JAVA alternatives and found a few.
- PMD & Checkstyle both operate on source code level.
- FindBugs operates on bytecode level.
On freesoftwaremagazine.com there is an article series on JAVA static code analysis software. It covers PMD and FixBugs and integration in Eclipse. It does not cover Checkstyle. Checkstyle is essentialy the same as PMD but it is better integrated in eclipse: it checks code on save and uses the standard ‘Problems’ interface, PMD does not.
To fix problems Eclipse save actions can save you some time. IBM has an article on how to keep your code clean using Eclipse.
Continuous testing is also a really nice thing to have: detecting unexpected behavior while refactoring/programming can prevent unnecessary bug hunts. A video about immediate feedback using continuous testing makes this clear.
Another tip is a more philosophical one: making your code and code revisions publicly available makes you think twice before implementing (and subsequently publishing) a quick and dirty hack. Tarsos is available on github.