Checkstyle is a development tool for helping programmers to write java code which follows a coding standard. In addition, is highly configurable and made to support any coding standard. It comes also with some predefined coding standards and is easy to use.
How to integrate Checkstyle in your environment? Let’s suppose you are using Maven as build tool. First step is to work on defining your own coding standard. If you don’t have any idea, don’t worry, you can follow an already defined one, like the one proposed by Google. Moreover, for my projects, I’ve also created one, few months ago. Feel free to download and use it. It’s absolutely free.
Next step is to add a new plugin in your POM file:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>3.1.2</version> <executions> <execution> <id>verify-style</id> <phase>process-classes</phase> <goals> <goal>check</goal> </goals> </execution> </executions> <configuration> <logViolationsToConsole>true</logViolationsToConsole> <configLocation>checkstyle.xml</configLocation> </configuration> <dependencies> <dependency> <groupId>com.puppycrawl.tools</groupId> <artifactId>checkstyle</artifactId> <version>8.40</version> </dependency> </dependencies> </plugin> </plugins> </build>
Make sure your checkstyle.xml is deployed under project root directory!
Run mvn clean install and look for some logs to be sure everything is working as expected. If everything works as expected and no violations are reported, then you will see something like this in application logs:
[INFO] --- maven-checkstyle-plugin:3.1.2:check (verify-style) @ myalerts-app --- [INFO] You have 0 Checkstyle violations.
The build will fail if at least one violation is reported. Don’t panic, this is the expected behavior because we want to make sure the coding standard is followed properly.