Skip to content

Choose your code style

B. K. Oxley (binkley) edited this page Jun 14, 2024 · 13 revisions

Style is an often overlooked but very critical attribute of writing. The style of writing directly impacts the readability and understandability of the end product.

There are 2 main java code styles, and many variants. Typically the discussion on style is 4-space or 2-space indentation (and sometimes <TAB>):

An example of a variant style is Palantir based on Google code style.

It is up to you which one you should choose. But the style should be chosen and the style should be the same for everyone.

To maintain the same standard config/ide/eclipse-java-google-style.xml or intellij-java-google-style.xml should be imported to your IDE. Checkstyle should be configured based on the chosen standard.

Checkstyle

With Java, one needs to rely on external tooling for linting. The most popular choice is:

However, Checkstyle will not auto-format code for you. For auto-formatting, consider, depending on your team preferences, any of these build plugins:

  • Rewrite — General framework. for transforming source code with many extensions and plugins for different languages and frameworks. For Gradle, see Rewrite for Gradle with a focus on SUN style guides for Java; for Maven, see Rewrite for Maven with a focus on SUN style guides for Java
  • Spotless — For Gradle, use the spotlessApply task to reformat; for Maven use the spotless:apply goal. The tool behind the plugin supports many source languages, not just Java.

For your editor, consider the sample .editorconfig file in this project. It is respected by IntelliJ and many other code editors.
(The sample uses 80-character line limits as IBM and Hollerith punch cards intended, and helpful for speed readers of code. A point worthy of team discussion.)

The demonstration projects assume checkstyle configuration at config/checkstyle/checkstyle.xml This is the default location for Gradle, and configured for Maven in the project.

The Checkstyle configuration used is stock sun_checks.xml (this is SUN default style for Java) with the addition of support for @SuppressWarnings(checkstyle:...). Note that this format is overly aggressive for Javadocs, and needs tweaking for most projects. See comments in build.gradle about SUN vs Google styles for Java.

Going further

TODO: Placeholder section

Clone this wiki locally