Standardize Java Code Formatting {Intellij, VSCode}
Lately, I have been working on bunch of Java Services that requires code refactoring and the first step to code refactoring is code formatting. The codebase has spotless configured but the formatting is not consistent while working in different IDEs. This is a Technical Debt that talks about Code Readability and Indentation. This needs to be addressed to fix the health of the codebase. The real affect of this inconsistent code format will be realised during PR reviews and while syncing others code into the current feature branches.
- Optional Read
I use VsCode and here is my brief setup that enables Autoformat.
- Formatting is enforced via Spotless plugin through build tools like gradle/maven.
- But, this is during BUILD time.
-
Here is my sample gradle spotless config
spotless { java { googleJavaFormat() importOrderFile(rootProject.file('importsorder')) removeUnusedImports() trimTrailingWhitespace() } }
-
importsorder
# @author: sairaghavak 10= 9=<app specific> 8=lombok 7=io 6=com 5=org 4=org.springframework 3=jakarta 2=javax 1=java 0=#
- How about formatting in IDE?
- I am not using Spotless for this. Rather I am doing what spotless is doing internally
-
Here is my on save action in vscode
"emeraldwalk.runonsave": { "commands": [ { "match": "\\.java$", "cmd": "java -jar /home/srk/google-java-format-1.25.0-all-deps.jar \ --skip-sorting-imports --replace ${file}" } ] }
-
settings.json
"java.saveActions.organizeImports": true, "java.completion.importOrder": [ "#", "java", "javax", "jakarta", "org.springframework", "org", "com", "io", "lombok", "app-sepecifc", "" ]
- This will ensure that the formatting is done via IDE
- Now
-
BUILD Tool formatting = IDE Formatting
-
.gradlew build
or.gradlew spotlessApply
=VScode On File Save
This is not enough, as most of the Java Devs use Intellij it’s important to ensure that the formatting done through Intellij IDEA is inline with the above Vscode and Build time formatting.
-
Defined an
.editorconfig
. Read for intellij specific options[*] indent_style=space ident_size=2 indent_use_tab=false end_of_line=lf charset=utf-8 trim_trailing_whitespace=true insert_final_newline=true max_line_length=100 # idea specific language agnostic settings ij_continuation_indent_size=2 [*java] ij_java_imports_layout=disabled
- This still doesn’t guarantee the formatting as expected.
- Here are my installed plugins, but File Watchers is want we want at this point
-
That’s it. Now, Intellij’s on save is just doing
gradlew spotlessApply
- In summary
(Vscode Java Formatting) = (Intellij Java Formatting)
This will ensure consistent code formatting across the 2 widely used IDEs in Java projects.