Checking code style with Maven and Checkstyle

Table of Contents

Keeping code clean and formatted in standardised way is one of the keys to successful project. It makes code easier to read, makes code easier to understand and allows new joiners to familiarize themselves with the project faster, especially when project’s coding standard is one of publicity available. In this post I will show how to configure Maven to run Checkstyle plugin, generate and review report and show few options that are not enabled by default but worth to check. Before we will start take a look on code below and try to find code style validation errors.

/**
 * Messy
 *          code
 *          makes
*           programmers
 * life
 *  <p>harder.</p>
 */
public class App {

    final static public String myConst = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore ";

    public static void main(String[] args) {
        System.out.println(myConst);
        System.out.println("Please fix me :)");
    }
}

Did you spot 8 validation errors? If yes, congrats! How much time did it take?
If no, don’t worry there’s solution for that. Checkstyle may spot all the coding style mistakes for you withing seconds. Enough talking let’s see how to configure and run checkstyle.

Example project

In this post I will use code base from the project on GitHub. The project is as follows:

├── pom.xml (Maven configuration)
└── src
    └── main
        └── java
            └── codes
                └── hubertwo
                    └── maven
                        └── checkstyle
                            └── App.java (Messy source code)

In real life, projects have much more files but for the demonstration purposes I keep it as simple as possible. We have Maven configuration pom.xml and App.java which contains messy code (presented at the beginning of the post).

Adding plugin to pom.xml

Adding checkstyle to your Maven configuration is no-brainer. Let’s simply add configuration below to pom.xml. The only configuration param added, the linkXRef is here to disable links to source code in report which requires more steps to configure. To keep this tutorial as simple as possible I decided to disable it.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-checkstyle-plugin</artifactId>
            <version>3.1.2</version>
            <configuration>
                <linkXRef>false</linkXRef> 
            </configuration>
        </plugin>
    </plugins>
</build>

Generating report

Once added the plugin definition we are ready to generate the report. To do so we will use checkstyle:checkstyle goal.

mvn checkstyle:checkstyle
...
[INFO] ----------< codes.hubertwo.maven.checkstyle:maven-checkstyle >----------
[INFO] Building maven-checkstyle 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] --- maven-checkstyle-plugin:3.1.2:checkstyle (default-cli) @ maven-checkstyle ---
[INFO] There are 8 errors reported by Checkstyle 8.29 with sun_checks.xml ruleset.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS

As you can see the plugin reported 8 errors. You may ask why the build is successful when there are some errors? This is because of the goal we used. You can check how to fail the build when errors are found here. Now let’s see the report.

Viewing report

When checkstyle:checkstyle goal is done the report in HTML format should be generated. You can find it under targer/site/checkstyle.html

tree
.
...
└── target
    ├── checkstyle-cachefile
    ├── checkstyle-checker.xml
    ├── checkstyle-result.xml
    └── site
        ├── checkstyle.html (Checkstyle report)
        ├── checkstyle.rss
        └── images
            └── rss.png

Checkstyle report 🔍

In the report you can find all coding style errors and validations with some suggestions how to fix them. Do the checkstyle results cover with your findings from the first exercise?

Extra configuration

Here I’ve collected few topics that might be useful.

Printing validation errors to log / adding checkstyle to CI pipeline

Sometimes it’s better to show validation errors in build log than downloading and opening the report. I prefer this way when I’m working on changes locally and want to fix code before submitting changes. It’s also handy when you want to include code style check in you continuous integration pipeline. To do so simply use checkstyle:check goal. In this goal the build will fail if any error found by deault.

mvn checkstyle:check
...
[INFO] --- maven-checkstyle-plugin:3.1.2:check (default-cli) @ maven-checkstyle ---
[INFO] There are 8 errors reported by Checkstyle 8.29 with sun_checks.xml ruleset.
[ERROR] src/main/java/codes/hubertwo/maven/checkstyle/App.java:[1] (javadoc) JavadocPackage: Missing package-info.java file.
[ERROR] src/main/java/codes/hubertwo/maven/checkstyle/App.java:[11,1] (design) HideUtilityClassConstructor: Utility classes should not have a public or default constructor.
[ERROR] src/main/java/codes/hubertwo/maven/checkstyle/App.java:[13] (sizes) LineLength: Line is longer than 80 characters (found 144).
[ERROR] src/main/java/codes/hubertwo/maven/checkstyle/App.java:[13,5] (javadoc) JavadocVariable: Missing a Javadoc comment.
[ERROR] src/main/java/codes/hubertwo/maven/checkstyle/App.java:[13,11] (modifier) ModifierOrder: 'static' modifier out of order with the JLS suggestions.
[ERROR] src/main/java/codes/hubertwo/maven/checkstyle/App.java:[13,32] (naming) ConstantName: Name 'myConst' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.
[ERROR] src/main/java/codes/hubertwo/maven/checkstyle/App.java:[15,5] (javadoc) MissingJavadocMethod: Missing a Javadoc comment.
[ERROR] src/main/java/codes/hubertwo/maven/checkstyle/App.java:[15,29] (misc) FinalParameters: Parameter args should be final.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

Checking for unused imports

By default, checkstyle does not check for unused imports in the code. To my surprise, none of Sun or Google checkstyle definition does not contain this rule. Moreover, checkstyle does not support rule definition inheritance, so if you use default style in your project you have to copy the whole file and add extra module for unused imports. If you use custom style, the change will require only one line.

<module name="UnusedImports"/>

TL;DR - Maven configuration

You can find the link to repository with example code at the bottom of this page. However, if you are just looking for ready to use solution, you can find full configuration below.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-checkstyle-plugin</artifactId>
            <version>3.1.2</version>
            <configuration>
                <linkXRef>false</linkXRef>
            </configuration>
        </plugin>
    </plugins>
</build>

Summary

In few steps we added the Maven Checkstyle plugin, checked the report and learned how to show style validation errors in build log.

Source code

All code samples and Maven project described in this post is available on GitHub Coding standard with Maven and Checkstyle.
If you found this post useful do not forget to leave a ⭐️ on GitHub :) Thanks!

Read more

  1. Maven Checkstyle plugin documentation
  2. Google Java Style Guide