DEV Community

Cover image for Checkstyle
Alexandru Muntean
Alexandru Muntean

Posted on

Checkstyle

Hello there!

This is the second tool I encountered in my search journey and it looks like we had lots of styling issues.

It is true that most of them can be easily resolved by having a common formatter style installed in the IDE, but for custom and more accurate styling, this tool can come in handy for you.

Checkstyle

It is an awesome tool from developers to developers, meant to automate a bit the process of checking Java code, sparing humans from it, and letting them focusing on important things.

Installation

There are a few ways to install it into your projects, such as:

  • Direct JAR which can be taken from Github
  • Using it through your IDE, check this list for the suitable one for you
  • Maven plugin set at build step in your project's pom.xml file

Usage

Depending on your chosen path, there are different ways to customize your code conventions. For this article, I chose to write more about the last option, which implies a simple addition in your pom.xml file within the plugins section:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-checkstyle-plugin</artifactId>
   <version>3.1.1</version>
   <configuration>
     <consoleOutput>true</consoleOutput>
     <violationSeverity>warning</violationSeverity>  <!-- now build fails for Warnings -->
     <failOnViolation>true</failsOnViolation>
     <configLocation>some-dir/your-checkstyle.xml</configLocation>
     <sourceDirectories>
        <sourceDirectory>src/main/java</sourceDirectory> <!-- Root directory from where the checking process starts -->
     </sourceDirectories>
   </configuration>
   <executions>
     <execution>
       <id>validate</id>
       <phase>validate</phase>
       <goals>
         <goal>check</goal>
       </goals>
     </execution>
   </executions>
 </plugin>
Enter fullscreen mode Exit fullscreen mode

Now, whenever the project is built, this checker will be triggered, and in case there at least one warning, then the build will Fail.

Code conventions

The official documentation provides a nice and easy to use list of all standards checks that this tool supports. You should always refer to it when you are looking for some explanations or details for a certain module out there.

On the other hand, there are a couple of presets files that can be used almost out of the box:

Or, you can create a custom one that suits your team and your project starting from the list or from the presets.


That's pretty much it, I hope you enjoy it and that it will come in handy for your current or incoming projects, but don't necessarily believe me, try it yourself.


Stay tuned for the next article in the series!

Cover photo by Markus Spiske on Unsplash

Top comments (0)