Tuesday, April 16, 2019

Example of using Checkstyle for coding standard


As it claims on its web site, Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard. It can be downloaded from http://checkstyle.sourceforge.net/. The downloadable binary is a JAR file, e.g. checkstyle-8.19-all.jar.

If you want to follow the Google Java Style (https://google.github.io/styleguide/javaguide.html), you can run Checkstyle with the built-in Google style like this:

$ java -jar checkstyle.jar -c /google_checks.xml MyClass.java

-- checkstyle.jar is the downloaded JAR file from the Checkstyle's site.
-- /google_checks.xml tells Checkstyle to use the built-in style.

You may write your own style but a more convenient way is to download one of the default style configuration and modify it to suit your needs.

For example, the built-in google_checks.xml defines the code indentation offset as 2. If we want to set it to 4 for our own use, we can download google_checks.xml from https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml. Open it with a text editor, look for the Indentation section and change the values from 2 to 4, and 4 to 8:

        <module name="Indentation">
            <property name="basicOffset" value="4"/>
            <property name="braceAdjustment" value="0"/>
            <property name="caseIndent" value="4"/>
            <property name="throwsIndent" value="8"/>
            <property name="lineWrappingIndentation" value="8"/>
            <property name="arrayInitIndent" value="4"/>
        </module>


Then we save the file as my_style_checks.xml.

To use a customized configuration, we run Checkstyle as:

$ java -jar checkstyle.jar -c /path/to/my_style_checks.xml MyClass.java

-- after -c we need to specify the absolute or relative path to the new style file we created.

No comments:

 
Get This <