Code Formatting with Spotless

Arun Prakash
2 min readNov 8, 2022

--

Not everyone follows or likes the same code formatting style. It changes from person to person.

Even the tiny formatting changes make a big readability difference

Scenario 1: Eclipse Java Format

@Getter
private final String value;
@Autowired
private Testclass testObj;
List<String> names = asList("John", "Jack", "Jacob");

List<String> captains = names.stream().map(name -> "Captain " + name).collect(toList());

Scenario 2: Google Java Format

@Getter private final String value;       @Autowired private Testclass testObj;List<String> names = asList("John", "Jack", "Jacob");

List<String> captains = names.stream()
.map(name -> "Captain " + name)
.collect(toList());

Do you find considerable differences between the above scenarios? This is just a sample, the formatting can impact the readability of the code to a greater extent.

Source: Google

Now, let's see a flexible way for setting it up in Gradle.

Step 1:

Add the spotless plugin to the Gradle file

plugins {id ‘com.diffplug.spotless’ version ‘5.14.3’}apply plugin: ‘com.diffplug.spotless’

Step 2:

Add the dependency library

implementation ‘com.diffplug.spotless:spotless-plugin-gradle:6.11.0’

Step 3:

Add the version of spotless

ext {spotlessVersion = “3.13.0”}

Step 4:

Add the following script to the Gradle file,

spotless {java {// This path needs to be relative to each projecttarget fileTree(‘.’) {include ‘**/src/*/java/**/*.java’}removeUnusedImports()googleJavaFormat(“1.15.0”).aosp()// eclipse()importOrder ‘java’, ‘’, ‘org.web3j’, ‘\\#’trimTrailingWhitespace()endWithNewline()}}

Step 5:

Run

./gradlew build./gradlew :spotlessApply

We are done !!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Arun Prakash
Arun Prakash

Written by Arun Prakash

I write about Cloud, DevOps and SRE Stuffs! Passionate about Security !

No responses yet

Write a response