For most Java projects, maintaining code style and coding guidelines is a must do step as part of application development. While this step does get overlooked by many developers, there are easy ways to integrate the practice of checking code style before releasing the code for testing.
One of the tools available for Java is CheckStyle. The tool checks for style deviations rather than compilation or syntax errors. For example, if we have written a single line block (like a “return” statement) in an “if” statement, but have not enclosed the same in curly brackets, Checkstyle will mark it as a style error, even though the compiler happily passes it.
One of the ways to use Checkstyle is to run it on the command-line and pass it the name of the Java file or the name of the directory containing the source code. Checkstyle will then spit out a report either in plain text or XML format.
If we decide to follow this method, we have to remember to execute Checkstyle each time there is a change in the Java code. Hence we need to integrate Checkstyle into the Java development process. Using Checkstyle should not be an overhead or a separate activity.
To do this, we can modify the build file of the Java project and include Checkstyle as one of the targets. Once Checkstyle target is part of the build script, we need to ensure that it is invokved before the final target of the project (which is many cases is “jar” or “test”, etc).
The advantage of putting Checkstyle in the build script is that style checking of the Java code happens as part of the standard build process of the application. In fact, we can configure the build script such that the build fails in case erronous code (as per Checkstyle) is found. The additional advantage of putting Checkstyle in the build file is that we can invoke an produce an HTML report instead of an XML report.
To include Checkstyle as part of the standard build process, put the following in your Ant build script (assuming that you have Checkstyle 5 on your system).