So maybe not quite as “comforting” as chicken soup, but definitely a most helpful tool that every Java developer should have in their arsenal.  So what is it?

Well, Checkstyle is a development tool to help Java developers write code that adheres to a coding standard. It does that by using static code analysis to determine potential program errors based on predefined checks.

Taken from talk on Developing Maintainable Apps

For instance, if you wanted to restrict the number of lines allowed for each method to 40 lines, then you would add the following to your checkstyle.xml file:

<module name=“MethodLength">
    <property name="max" value=“40"/>

This will ensure that a warning is thrown when Checkstyle encounters methods that contain more than 40 lines of code. Thus assisting you in developing methods and by extension classes that are easier to debug, test, and refactor.

How do you include Checkstyle in your applications? If you’re using Gradle, it’s trivial; as it’s available as a plugin. Here’s a sample configuration:

apply plugin: ‘checkstyle’

task checkstyle(type: Checkstyle) {
  description 'Checks if the code passes standards'
  group 'verification'

  configFile file(‘checkstyle.xml')

Although Checkstyle comes baked with several useful modules that ensure code quality, you also have the flexibility to create your own rules.

For instance, if you feel having several empty lines in the middle of methods hinders readability (as I do) then you can create a check for that.

<module name="RegexpMultiline">
    <property name="format" value="\r?\n[ \t\x0B\f]*\r?\n[ \t\x0B\f]*\r?\n"/>
    <property name="fileExtensions" value="java"/>
    <property name="message" value="Two consecutive empty lines"/>

Once you begin incorporating Checkstyle into your build process you will appreciate having code that is easy to read and modular. This is especially the case since we spend more time reading and editing code as developers, than we do writing new code.

So here's a sample checkstyle.xml file that you can use to get started. Let me know how it goes!