Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a consistent Java code format be enforced?

I'm looking for a way to force developers to use the same Java code formatting rules. My requirements are:

  1. Gradle integration
    1. Task that checks if code is correctly formatted. This will be used on CI to cause a build failure if incorrectly formatted code is submitted

    2. Task that fixes incorrectly formatted code (nice-to-have)

  2. IntelliJ integration
    1. Incorrectly formatted code can be fixed within the IDE via the "Reformat Code" action
    2. Code that is generated by the IDE (e.g. getter/setter generation) conforms to the rules
  3. Supports the OpenJDK/Oracle Java formatting rules

Currently I'm using Spotless with the following configuration

spotless {
  java {
    toggleOffOn()
    eclipse().configFile("${project.rootDir}/tools/eclipse-java-formatter.xml")
    indentWithSpaces()
    removeUnusedImports()
  }
}

For IntelliJ integration, I've installed the Eclipse Code Formatter plugin and configured it to use the same rules as Spotless.

This approach meets all of the requirements above except for 2.2 i.e. any code generated by IntelliJ must be reformatted before it conforms to the formatting rules. A further problem is that the imports seem to be arbitrarily reordered when code is reformatted. This generates a lot of spurious changes which makes pull requests more difficult to review.

Is there another approach (e.g. CheckStyle) that does not suffer from these shortcomings?

like image 501
Antonio Dragos Avatar asked Nov 20 '20 10:11

Antonio Dragos


People also ask

How do I Format Java code?

Window -> Preferences -> Java -> Editor -> Save Action -> Format source code (Format all lines & Imports)

Why should you Format your code?

Consistently using the same style throughout your code makes it easier to read. Code that is easy to read is easier to understand by you as well as by potential collaborators. Therefore, adhering to a coding style reduces the risk of mistakes and makes it easier to work together on software.

What is spotless Java?

Spotless is a general-purpose formatting plugin used by 4,000 projects on GitHub (August 2020).


Video Answer


2 Answers

You could use the Google Java Format, which has plugins for the aforementioned IDEs (IntelliJ IDEA, Eclipse), it provides integrations with tools such as Maven, Gradle, or SBT, and provides means to run the formatter as pre-commit hook or when pushing the code to Github with Github actions.

In their README they also mention the imports issue and how to fix it for IntelliJ IDEA, and more insights are provided e.g.: on how to handle it on Spotless Gradle plugin, when using the Maven Spotless plugin, or for Github actions.

A drawback for your specific case may be that the tool enforces the Google Java style guide, which was praised and recommended by the Oracle Java team as described in the Oracle Java magazine. It also provides the option to use the AOSP code style.

Below a snippet for spotless Gradle configuration, considering imports ordering:

spotless {
    java {
        importOrder() // standard import order
        importOrder('java', 'javax', 'com.acme', '') // or importOrderFile
        // You probably want an empty string at the end - all of the
        // imports you didn't specify explicitly will go there.

        removeUnusedImports()

        googleJavaFormat() // has its own section below
        eclipse()          // has its own section below
        prettier()         // has its own section below
        clangFormat()      // has its own section below

        licenseHeader '/* (C) $YEAR */' // or licenseHeaderFile
    }
}
like image 169
sashimi Avatar answered Oct 13 '22 02:10

sashimi


Checkstyle supports most of your requirements.

Gradle Integration:

plugins {
    id 'checkstyle'
}

checkstyle {
    toolVersion = checkstyleVersion
    config = rootProject.resources.text.fromFile(checkstyleRulesRootPath)  # Loads configuration from a file
    ignoreFailures = false # Causes build to fail
    maxWarnings = 0 # Fails even for warnings
}

It do not fixes code automatically (AFAIK).

IntelliJ integration:

There's Checkstyle plugin which you can configure to display warnings as you're coding.

You can also configure IntelliJ autoformatting to use these rules.

Formatting rules

Here is the configuration for Oracle/Sun specifications in checkstyle.

like image 1
Yayotrón Avatar answered Oct 13 '22 03:10

Yayotrón