My new website on Artificial Intelligence and Machine Learning www.aimlfront.com

Checkstyle

Checkstyle is a plugin to help programmers write Java code that adheres to a coding standard. It automates the process of checking Java code to spare humans of this task and make sure follow systematic way and programming style.

Checkstyle is highly configurable and can be made to support almost any coding standard. An example configuration file is supplied supporting the Sun Code Conventions. As well, other sample configuration files are supplied for other well known conventions.

A Checkstyle plug-in can provide new functionalities, like::

  • Especially for javaDocs
  • Unnecessary tabs/spaces
  • Limit of the number of function parameters, line lengths
  • The use of packets imports, of classes, of scope modifiers and of instructions blocks.
  • 'if' construct must use '{}'s.
  • Naming conventions of attributes and methods.
  • Multiple complexity measurements, among which expressions.
  • The good practices of class construction.

Checkstyle setup for the Maven

Add plugin information (inside plugins tag) to pom.xml for the project wise. Otherwise if have common parent, can add it there itself, so that it will be shared to sub modules which are inclued in parent..

<plugin>
      <artifactId>maven-checkstyle-plugin</artifactId>
      <configuration>
            <includeTests>true</includeTests>
            <rulesets>
            <ruleset>${checkstyle-config-url}</ruleset>
            </rulesets>
            <minimumTokens>100</minimumTokens>
            <targetJdk>${targetJdk}</targetJdk>
            <failOnViolation>true</failOnViolation>
      </configuration>
      <executions>
            <execution>
            <phase>test</phase>
                <goals>
            	    <goal>check</goal>
                </goals>
            </execution>
      </executions>      
</plugin>


If you want to exclude test cases from checkstyle violations remove below line from above setup

<includeTests>true</includeTests>

If you don't want to see any failure on build even though violations reported by checkstyle, make below property as false

<failOnViolation>false</failOnViolation>

Add the below property to pom.xml, which includes custom rules. If we don't declare ruleset for checkstyle, default rules will be executed which are there inside plugin.

<properties>
   <checkstyle-config-url>
      C:/rules/checkstyle/2.0/checkstyle-2.0.xml
   </checkstyle-config-url>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

Do maven clean install. If you have any checkstyle vioaltions, build will fail.

After doing maven install. If we have any Checkstyle errors, build will fail. Goto the below locations will get the details about Checkstyle violations for the project.

	${workspacelocation}\${Projectlocation}\target\checkstyle.xml

		(or)

	${workspacelocation}\${Projectlocation}\target\site\checkstyle.html