Skip to main content

Checkstyle and Spotless Guide

Overview

This guide covers both Checkstyle (style validation) and Spotless (auto-formatting) tools that work together to maintain Google Java Style Guide compliance across the codebase.

Related Issues:

Tools Overview

ToolPurposeModeCapabilities
Spotless🔧 Auto-formatterActiveFixes formatting automatically
Checkstyle🔍 Style validatorWarningReports all style violations

Both tools use the Google Java Style Guide but serve complementary roles.


Spotless (Auto-Formatting)

Configuration

Plugin: com.diffplug.spotless:spotless-maven-plugin:2.43.0
Formatter: Google Java Format v1.19.2
Scope: src/main/java/**/*.java and src/test/java/**/*.java
Exclusions: Generated protobuf code

Basic Commands

Prerequisites - Ensure project compiles:

export JAVA_HOME=/usr/lib/jvm/temurin-23-jdk-arm64
mvn clean compile

Format entire codebase:

export JAVA_HOME=/usr/lib/jvm/temurin-23-jdk-arm64
mvn spotless:apply

Format specific file:

export JAVA_HOME=/usr/lib/jvm/temurin-23-jdk-arm64
mvn spotless:apply -DspotlessFiles=src/main/java/path/to/YourFile.java

Format multiple files:

export JAVA_HOME=/usr/lib/jvm/temurin-23-jdk-arm64
mvn spotless:apply -DspotlessFiles='src/main/java/org/codetricks/auth/**/*.java'

Check formatting without changing files:

mvn spotless:check

Incremental Workflows

Format only modified files:

# Format staged files
git diff --cached --name-only --diff-filter=ACM | grep '\.java$' | \
xargs -I {} mvn spotless:apply -DspotlessFiles={}

# Format unstaged files
git diff --name-only --diff-filter=ACM | grep '\.java$' | \
xargs -I {} mvn spotless:apply -DspotlessFiles={}

# Format files different from main branch
git diff --name-only main...HEAD | grep '\.java$' | \
xargs -I {} mvn spotless:apply -DspotlessFiles={}

What Spotless Fixes

Automatically Fixed:

  • Incorrect indentation (converts 4-space → 2-space)
  • Import ordering and lexicographical sorting
  • Import grouping and spacing
  • Unused import removal
  • Line wrapping and code spacing
  • Operator placement
  • String concatenation formatting

Troubleshooting Spotless

Problem: "BUILD SUCCESS" but no files changed

Causes & Solutions:

  1. Project not compiled

    # Solution: Compile first
    mvn clean compile
    mvn spotless:apply
  2. Import contiguity issues

    // ❌ This breaks Spotless (comment between imports):
    import java.util.List;
    // Issue #123: Some explanation
    import org.example.MyClass;

    // ✅ This works (comment moved):
    import java.util.List;
    import org.example.MyClass;

    // Issue #123: Some explanation
  3. Syntax errors in file

    • Spotless silently skips files with compilation errors
    • Check for missing imports, typos, or syntax issues

Problem: Maven errors during Spotless

Common errors:

  • FormatterException: error: Imports not contiguous - Fix import spacing
  • Build timeout - Large files may need more memory: export MAVEN_OPTS="-Xmx4g"

Checkstyle (Style Validation)

Configuration

Plugin: org.apache.maven.plugins:maven-checkstyle-plugin:3.5.0
Rules: Google Java Style Guide (config/checkstyle/google_checks.xml)
Mode: Warning (reports violations, doesn't fail build)
Suppressions: config/checkstyle/suppressions.xml

Basic Commands

Check entire codebase:

export JAVA_HOME=/usr/lib/jvm/temurin-23-jdk-arm64
mvn checkstyle:check

Check specific file:

export JAVA_HOME=/usr/lib/jvm/temurin-23-jdk-arm64
mvn checkstyle:check -Dcheckstyle.includes="**/YourFile.java"

Check specific package:

export JAVA_HOME=/usr/lib/jvm/temurin-23-jdk-arm64
mvn checkstyle:check -Dcheckstyle.includes="**/auth/rbac/*.java"

Generate detailed HTML report:

export JAVA_HOME=/usr/lib/jvm/temurin-23-jdk-arm64
mvn checkstyle:checkstyle
# Report generated in target/site/checkstyle.html

What Checkstyle Reports

Cannot Auto-Fix (Manual Required):

  • Missing Javadoc comments (@MissingJavadocType, @MissingJavadocMethod)
  • Lines too long to auto-wrap (@LineLength)
  • Variable declaration distance (@VariableDeclarationUsageDistance)
  • Method ordering (@OverloadMethodsDeclarationOrder)
  • Complex naming issues
  • Structural code issues

Understanding Violations

Violation Format:

[WARN] /path/to/File.java:123:45: Some description [RuleName]

Common Violations:

  1. CustomImportOrder: Import statements in wrong order

    • Usually fixed automatically by Spotless
    • If persists, check for import contiguity issues
  2. Indentation: Incorrect indentation levels

    • Usually fixed automatically by Spotless
    • If persists, file may have mixed indentation
  3. MissingJavadocMethod: Public method missing Javadoc

    • Requires manual fix - add proper Javadoc comments
  4. LineLength: Line exceeds 100 characters

    • Some automatically wrapped by Spotless
    • Others need manual refactoring

Integrated Workflow

Daily Development Workflow

1. When starting work on a file:

# Format the file first
mvn spotless:apply -DspotlessFiles=src/main/java/path/to/YourFile.java

# Check for remaining violations
mvn checkstyle:check -Dcheckstyle.includes="**/YourFile.java"

2. Before committing:

# Format all modified files
git diff --name-only | grep '\.java$' | while read file; do
mvn spotless:apply -DspotlessFiles="$file"
done

# Final style check
mvn checkstyle:check

Working with Legacy Code

Approach: Fix formatting incrementally, don't format entire codebase at once

Strategy A: Format per feature branch

# 1. Make your code changes
# 2. Format the files you touched
git diff --name-only | grep '\.java$' | xargs -I {} mvn spotless:apply -DspotlessFiles={}

# 3. Review combined diff (your changes + formatting)
git diff

# 4. Commit together
git commit -m "feat: implement feature X

- Add new functionality
- Auto-format modified files with Spotless"

Strategy B: Format by package

# Week 1: Format auth package
mvn spotless:apply -DspotlessFiles='src/main/java/org/codetricks/auth/**/*.java'
git add .
git commit -m "style: auto-format auth package with Spotless"

# Week 2: Format service package
mvn spotless:apply -DspotlessFiles='src/main/java/org/codetricks/construction/code/assistant/service/**/*.java'
git add .
git commit -m "style: auto-format service package with Spotless"

Code Review Checklist

For Authors:

  • Run Spotless on modified files
  • Check remaining Checkstyle violations are acceptable
  • Build and tests still pass

For Reviewers:

  • Verify formatting is consistent
  • Check that new code doesn't introduce major style violations
  • Ensure any suppressed warnings are justified

Advanced Usage

Integration with IDE

IntelliJ IDEA / Cursor:

  1. Install plugin: google-java-format
  2. Settings → Other Settings → google-java-format Settings
  3. ✅ Enable google-java-format
  4. ✅ Format on save

Benefits: Automatic formatting while typing, consistent with Spotless

CI/CD Integration (Future)

Planned for Phase 6:

# .github/workflows/code-quality.yml
- name: Check Code Formatting
run: mvn spotless:check

- name: Style Validation
run: mvn checkstyle:check

Custom Configuration

Adjust Spotless behavior in pom.xml:

<googleJavaFormat>
<version>1.19.2</version>
<style>GOOGLE</style>
<!-- Disable long string reflowing if preferred -->
<reflowLongStrings>false</reflowLongStrings>
</googleJavaFormat>

<!-- Keep unused imports (not recommended) -->
<!-- <removeUnusedImports /> -->

Suppress Checkstyle rules in config/checkstyle/suppressions.xml:

<suppress checks="LineLength" files=".*Test\.java" lines="1-1000"/>
<suppress checks="MissingJavadocMethod" files=".*Test\.java"/>

Implementation History

Phase 2.5: Spotless Implementation (October 2025)

Results: ✅ Complete Success

  • Files formatted: 149+ Java files across entire codebase
  • Violations resolved: Hundreds of indentation/import/spacing issues
  • Build impact: ~5-10 seconds added to build time
  • Side effects: Converted Markdown docstrings to proper Javadoc HTML

Key Technical Insights Discovered:

  1. Import Contiguity Requirement: Google Java Format fails silently if comments exist between import statements
  2. Compilation Dependency: Spotless requires compilable code before formatting
  3. Scope Difference: Spotless fixes formatting, Checkstyle validates everything

Phase 3: Checkstyle Integration (Earlier 2025)

Results: ✅ Warning Mode Active

  • Baseline: Project-wide style checking implemented
  • Mode: Warning mode (reports violations, doesn't fail build)
  • Configuration: Google Java Style Guide with custom suppressions

Quick Reference

Essential Commands

# Set Java environment (required in dev container)
export JAVA_HOME=/usr/lib/jvm/temurin-23-jdk-arm64

# Format single file
mvn spotless:apply -DspotlessFiles=src/main/java/path/to/File.java

# Check single file style
mvn checkstyle:check -Dcheckstyle.includes="**/File.java"

# Format all Java files
mvn spotless:apply

# Check all style violations
mvn checkstyle:check

File Patterns

# All files in package
-DspotlessFiles='src/main/java/org/codetricks/auth/**/*.java'
-Dcheckstyle.includes="**/auth/**/*.java"

# Multiple specific files
-DspotlessFiles='src/main/java/File1.java,src/main/java/File2.java'

# Single file by name pattern
-Dcheckstyle.includes="**/ArchitecturalPlanReviewer.java"

Resources