Java Formatters Compared: google-java-format vs Spotless | Web Formatter Blog

Java Formatters Compared: google-java-format vs Spotless
A comprehensive comparison of two popular Java code formatters to help you choose the right tool for your projects.
Introduction to Java Formatting
Consistent code formatting is a cornerstone of maintainable Java projects. As codebases grow and team sizes increase, having standardized formatting becomes increasingly important for readability, collaboration, and code review efficiency.
In the Java ecosystem, two formatting tools have gained
significant popularity: Google's google-java-format
{" "}
and Diffplug's Spotless
. While both aim to solve the
same fundamental problem, they differ in philosophy, flexibility,
and implementation.
This guide provides a comprehensive comparison of these tools to help you make an informed decision about which formatter best suits your project's needs.
Why Format Your Java Code?
Before diving into the specifics of each tool, let's consider why consistent code formatting matters:
- Improved readability: Consistent formatting makes code easier to scan and understand
- Faster code reviews: Reviewers can focus on logic rather than style issues
- Reduced merge conflicts: Consistent formatting minimizes unnecessary whitespace changes
- Easier onboarding: New team members can quickly adapt to a consistent codebase
- Enforced standards: Automated formatting ensures adherence to team or industry standards
- Reduced cognitive load: Developers can focus on solving problems rather than formatting decisions
While Java's syntax is relatively rigid compared to some languages, there are still numerous formatting decisions to make: indentation style, line wrapping, brace placement, import ordering, and more. Automated formatters eliminate these decisions and ensure consistency.
Understanding google-java-format
Google's java-format is an opinionated formatter that implements the Google Java Style Guide. Developed and maintained by Google, it's designed to produce consistent, Google-style formatted code with minimal configuration options.
Key characteristics of google-java-format include:
- Opinionated approach: Follows Google's Java style guide with few customization options
- Deterministic output: Given the same input, it always produces the same formatted output
- Speed: Generally fast performance, especially for incremental formatting
- Simplicity: Minimal configuration required, making it easy to adopt
- IDE plugins: Available for IntelliJ IDEA, Eclipse, and other popular Java IDEs
The tool is built on top of Google's Java compiler infrastructure, which gives it a deep understanding of Java syntax and ensures accurate formatting even for complex code structures.
Understanding Spotless
Spotless, developed by Diffplug, takes a more flexible approach to code formatting. Rather than being a formatter itself, Spotless is a formatting framework that can apply various formatters to different parts of your codebase.
Key characteristics of Spotless include:
- Flexibility: Can use multiple formatters, including google-java-format, Eclipse formatter, or custom rules
- Multi-language support: Beyond Java, it can format Kotlin, Scala, Groovy, and more
- Incremental formatting: Can efficiently format only changed files
- Build system integration: Seamless integration with Gradle and Maven
- Customizable rules: Supports custom formatting rules and transformations
Spotless can actually use google-java-format as its underlying Java formatter, while adding additional capabilities like import ordering, license header management, and more.
Installation & Setup
Setting Up google-java-format
To use google-java-format with Maven, add the following plugin to your pom.xml:
com.coveo
fmt-maven-plugin
2.13
format
For Gradle, add this to your build.gradle:
plugins {
id 'java'
id 'com.github.sherter.google-java-format' version '0.9'
}
googleJavaFormat {
toolVersion = '1.15.0'
}
You can also use it as a standalone command-line tool:
# Download the jar
curl -LJO https://github.com/google/google-java-format/releases/download/v1.15.0/google-java-format-1.15.0-all-deps.jar
# Format a file
java -jar google-java-format-1.15.0-all-deps.jar --replace MyFile.java
Setting Up Spotless
For Maven, add the following to your pom.xml:
com.diffplug.spotless
spotless-maven-plugin
2.30.0
1.15.0
check
For Gradle, add this to your build.gradle:
plugins {
id 'java'
id 'com.diffplug.spotless' version '6.18.0'
}
spotless {
java {
// Use google-java-format as the formatter
googleJavaFormat('1.15.0').aosp()
// Or use Eclipse's formatter
// eclipse().configFile('eclipse-formatter.xml')
// Add other formatting rules
importOrder('java', 'javax', 'org', 'com', '')
removeUnusedImports()
trimTrailingWhitespace()
endWithNewline()
}
}
Basic Usage
Using google-java-format
With Maven:
# Format all Java files
mvn com.coveo:fmt-maven-plugin:format
# Check if files are formatted correctly
mvn com.coveo:fmt-maven-plugin:check
With Gradle:
# Format all Java files
./gradlew googleJavaFormat
# Check if files are formatted correctly
./gradlew verifyGoogleJavaFormat
From the command line:
# Format a single file
java -jar google-java-format-1.15.0-all-deps.jar --replace MyFile.java
# Format multiple files
java -jar google-java-format-1.15.0-all-deps.jar --replace src/main/java/**/*.java
# Print formatted code to stdout without modifying files
java -jar google-java-format-1.15.0-all-deps.jar MyFile.java
Using Spotless
With Maven:
# Check if files are formatted correctly
mvn spotless:check
# Format all files
mvn spotless:apply
With Gradle:
# Check if files are formatted correctly
./gradlew spotlessCheck
# Format all files
./gradlew spotlessApply
Spotless can also be configured to run automatically during the build process, failing the build if files aren't properly formatted.
Configuration Options
google-java-format Configuration
Google's formatter is intentionally limited in configuration options, adhering to the philosophy that consistent style across all Google Java code is more valuable than customizability. The main options include:
- Style: Choose between Google style (default) and AOSP (Android Open Source Project) style
- Skip sorting imports: Option to skip sorting import statements
- Format specific files: Specify which files to format
Example of specifying AOSP style in Gradle:
googleJavaFormat {
toolVersion = '1.15.0'
options style = 'AOSP'
}
Spotless Configuration
Spotless offers extensive configuration options:
- Multiple formatters: Use different formatters for different file types
- Custom steps: Define custom formatting steps in sequence
- Import ordering: Specify import order patterns
- License headers: Add or update license headers
- Encoding: Specify file encoding
- Line endings: Normalize line endings (UNIX, Windows, etc.)
Example of a more complex Spotless configuration:
spotless {
java {
// Use a specific version of google-java-format
googleJavaFormat('1.15.0')
// Define import order
importOrder('java', 'javax', 'org', 'com', '')
// Remove unused imports
removeUnusedImports()
// Add license header
licenseHeader '/* Copyright $YEAR */'
// Custom formatting rule
custom 'no System.out.println', { it.replace('System.out.println', 'logger.debug') }
// Exclude generated files
targetExclude 'src/generated/**/*.java'
}
// Format other file types
format 'misc', {
target '**/*.md', '**/*.xml'
trimTrailingWhitespace()
indentWithSpaces(2)
endWithNewline()
}
}
Head-to-Head Comparison
Formatting Style
The formatting styles of both tools can be similar if Spotless is configured to use google-java-format. However:
- google-java-format: Strictly follows Google's Java style guide with minimal variations
- Spotless: Can be configured to use Google style, Eclipse style, or custom rules
If your team already follows Google's style guide or wants a standardized approach with minimal decisions, google-java-format is ideal. If you need to match existing code style or have specific formatting requirements, Spotless offers more flexibility.
Flexibility & Customization
Feature | google-java-format | Spotless |
---|---|---|
Style options | Limited (Google or AOSP) | Extensive |
Custom rules | No | Yes |
Multi-language support | Java only | Multiple languages |
Import ordering | Fixed | Customizable |
License headers | No | Yes |
Performance
Performance can vary depending on project size and configuration:
- google-java-format: Generally fast, especially for incremental formatting
- Spotless: Can be slower due to its flexibility and multiple formatting steps, but offers good incremental performance
For large projects, both tools support incremental formatting, which significantly improves performance by only formatting changed files.
Integration Options
Both tools offer various integration options:
- Build systems: Both support Maven and Gradle
- IDEs: Both have plugins for IntelliJ IDEA and Eclipse
- CI/CD: Both can be integrated into CI/CD pipelines
- Git hooks: Both can be used with pre-commit hooks
Spotless has an edge in terms of broader language support and more extensive build system integration options.
Code Examples
Before & After Examples
Let's look at how both formatters handle the same unformatted Java code:
As you can see, when Spotless is configured to use google-java-format, the output is identical. The key differences emerge when you customize Spotless to use different formatting rules.
Complex Formatting Examples
Here's a more complex example showing how the formatters handle challenging code structures:
Both formatters handle complex code structures well, with appropriate line wrapping, indentation, and spacing to improve readability.
Editor Integration
IntelliJ IDEA
For google-java-format:
- Install the "google-java-format" plugin from the JetBrains Marketplace
- Go to Settings → Other Settings → google-java-format Settings
- Enable "Enable google-java-format" and select your preferred style
For Spotless:
- No direct plugin, but you can configure IntelliJ's formatter to match your Spotless configuration
- Alternatively, use the "Save Actions" plugin to run Spotless on save
Eclipse
For google-java-format:
- Download the google-java-format Eclipse plugin
- Place it in the Eclipse dropins folder
- Restart Eclipse and enable the formatter in Preferences
For Spotless:
- If using Eclipse formatter with Spotless, export your Eclipse formatter settings and use them in Spotless
- Use the "Save Actions" feature to format on save
Visual Studio Code
For google-java-format:
- Install the "Java Extension Pack"
- Configure settings.json to use google-java-format
For Spotless:
- Use the "Java Extension Pack"
- Configure tasks.json to run Spotless as a build task
- Optionally set up a keyboard shortcut to format the current file
Best Practices
Regardless of which formatter you choose, follow these best practices for a smooth experience:
- Format the entire codebase before adopting the formatter to minimize disruptive changes
- Add formatting checks to CI to prevent unformatted code from being merged
- Use IDE integration for immediate feedback during development
- Document your formatting standards in your project README
- Apply formatting before code reviews to focus reviews on substance rather than style
- Keep the formatter version consistent across all developers and CI environments
Troubleshooting Common Issues
Here are solutions to common formatter issues:
Issue | Solution |
---|---|
Formatter breaking comments | Ensure multi-line comments use proper formatting; consider using block comments |
Inconsistent behavior across IDEs | Standardize on build tool integration rather than IDE-specific formatters |
Performance issues with large files | Use incremental formatting when available; consider breaking up very large files |
Formatting disrupting git blame | Use git-blame-ignore-revs to ignore mass-formatting commits |
Build failures due to format violations | Add a format task to pre-commit hooks; run formatter before committing |
Conclusion
Both google-java-format and Spotless are excellent tools for maintaining consistent Java code formatting. Your choice should be based on your specific needs:
- Choose google-java-format if you want a simple, opinionated formatter that follows Google's style guide with minimal configuration
- Choose Spotless if you need more flexibility, multi-language support, or additional formatting capabilities beyond basic code style
Remember that the most important aspect is consistency. Either tool, when applied consistently across your codebase and team, will significantly improve code readability and collaboration.
By integrating your chosen formatter into your development workflow, IDE, and CI/CD pipeline, you can ensure that all code follows the same standards, allowing your team to focus on what really matters: building great software.