Skip to main content

Checkstyle - Google Java Style Guide

Overview

Checkstyle enforces the Google Java Style Guide for consistent code formatting and readability.

Status: ✅ Phase 3 Complete (WARNING mode)
Related: Issue #203 - Phase 3
Version: Checkstyle 10.18.2, maven-checkstyle-plugin 3.5.0


Quick Start

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

# Generate HTML report
mvn checkstyle:checkstyle
open target/site/checkstyle.html

Current Configuration

Mode: WARNING

Checkstyle is currently in WARNING mode:

  • ✅ Violations are reported in console
  • ✅ HTML reports generated
  • ⚠️ Build does NOT fail on violations
  • 📊 Violations tracked for baseline

Location: pom.xml lines 226-273

To enable strict mode later:

\u003c!-- Change these in pom.xml --\u003e
\u003cfailsOnError\u003etrue\u003c/failsOnError\u003e
\u003cfailOnViolation\u003etrue\u003c/failOnViolation\u003e

What Gets Checked

Included ✅

  • All code in src/main/java/org/codetricks/
  • Our business logic
  • Service implementations
  • Utility classes

Excluded ❌

  • Generated protobuf code (target/generated-sources/)
  • Vendored third-party code:
    • com/google/adk/ (Google ADK)
    • org/apache/pdfbox/ (PDF utilities)
    • dev/langchain4j/ (LangChain4j)
  • Test resources

Configuration: config/checkstyle/suppressions.xml


Baseline Results

Current Status (Oct 2025)

$ mvn checkstyle:check
[INFO] You have 0 Checkstyle violations.
[INFO] BUILD SUCCESS

Excellent! Our codebase already follows Google Java Style Guide!

Minor issues found (suppressed in warning mode):

  • Import ordering in a few files
  • All in our own code (org.codetricks.*)
  • Easy to fix incrementally

Configuration Files

1. Google Checks (config/checkstyle/google_checks.xml)

Official Google Java Style Guide rules, version-matched to Checkstyle 10.18.2.

Source: https://github.com/checkstyle/checkstyle/blob/checkstyle-10.18.2/src/main/resources/google_checks.xml

Key rules:

  • Indentation: 2 spaces
  • Line length: 100 characters
  • Import ordering: Static first, then by package
  • Javadoc requirements on public APIs
  • Naming conventions (camelCase, etc.)

2. Suppressions (config/checkstyle/suppressions.xml)

Excludes generated and third-party code:

\u003csuppressions\u003e
\u003c!-- Generated protobuf code --\u003e
\u003csuppress checks=".*" files="target[\\/]generated-sources[\\/]protobuf[\\/].*"/\u003e

\u003c!-- Third-party vendored code --\u003e
\u003csuppress checks=".*" files="src[\\/]main[\\/]java[\\/]com[\\/]google[\\/]adk[\\/].*"/\u003e
\u003csuppress checks=".*" files="src[\\/]main[\\/]java[\\/]org[\\/]apache[\\/]pdfbox[\\/].*"/\u003e
\u003csuppress checks=".*" files="src[\\/]main[\\/]java[\\/]dev[\\/]langchain4j[\\/].*"/\u003e
\u003c/suppressions\u003e

Usage

Run During Build

Checkstyle runs automatically during mvn compile (validate phase):

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

Output includes Checkstyle warnings (if any).

Run Standalone

# Check only (console output)
mvn checkstyle:check

# Generate HTML report
mvn checkstyle:checkstyle
open target/site/checkstyle.html

Check Specific Files

# Using Maven (checks whole project)
mvn checkstyle:check

# Using Checkstyle CLI directly (single file)
java -jar ~/.m2/repository/com/puppycrawl/tools/checkstyle/10.18.2/checkstyle-10.18.2-all.jar \
-c config/checkstyle/google_checks.xml \
src/main/java/org/codetricks/YourFile.java

Common Violations

Import Ordering

Issue: Imports not in Google Style order

Rule: Static imports first, then:

  1. java.*
  2. javax.*
  3. Third-party packages (alphabetical)
  4. Local packages (org.codetricks.*)

Fix:

// Before (wrong order)
import org.codetricks.MyClass;
import java.util.List;
import static java.util.Collections.*;

// After (Google Style)
import static java.util.Collections.*;

import java.util.List;

import org.codetricks.MyClass;

IntelliJ IDEA: Settings → Editor → Code Style → Java → Imports

  • Configure to match Google Style
  • Or use: File → Settings → Plugins → Install "google-java-format"

Line Length

Rule: Max 100 characters per line

Fix:

// Before (too long)
String message = "This is a very long string that exceeds the 100 character limit and should be broken up for readability";

// After
String message = "This is a very long string that exceeds the 100 character limit "
+ "and should be broken up for readability";

Indentation

Rule: 2 spaces (not tabs, not 4 spaces)

Fix in IDE:

  • IntelliJ: Settings → Editor → Code Style → Java → Tabs and Indents
    • Tab size: 2
    • Indent: 2
    • Use spaces (not tabs)

IDE Integration

IntelliJ IDEA

Option 1: Import Checkstyle Config

  1. Install "Checkstyle-IDEA" plugin
  2. Settings → Tools → Checkstyle
  3. Add configuration file: config/checkstyle/google_checks.xml
  4. Make it active
  5. View violations in real-time

Option 2: Google Java Format Plugin

  1. Install "google-java-format" plugin
  2. Settings → google-java-format Settings
  3. Enable "Enable google-java-format"
  4. Format on save (optional)

This automatically formats code to Google Style on save!

VS Code

  1. Install "Checkstyle for Java" extension
  2. Configure in .vscode/settings.json:
{
"java.checkstyle.configuration": "${workspaceFolder}/config/checkstyle/google_checks.xml"
}

Fixing Violations

Strategy: Fix Forward

Following the same strategy as Error Prone:

  1. When editing a file, fix any style violations in that file
  2. Before committing, run mvn checkstyle:check
  3. Address issues in files you touched
  4. Don't mass-fix the entire codebase at once

Batch Fix (When Ready)

Once comfortable with the rules:

# Use IntelliJ's auto-format
1. Open IntelliJ IDEA
2. Code → Reformat Code (Ctrl+Alt+L)
3. Select "Whole project"
4. Check "Optimize imports"
5. Run checkstyle:check to verify

Or use google-java-format CLI:

# Download google-java-format
wget https://github.com/google/google-java-format/releases/download/v1.23.0/google-java-format-1.23.0-all-deps.jar

# Format all files
find src/main/java/org/codetricks -name "*.java" -exec \
java -jar google-java-format-1.23.0-all-deps.jar --replace {} \;

Graduation to Strict Mode

Current Phase

Phase 3.1: Observation (WARNING mode) ← We are here

  • ✅ Checkstyle running on every build
  • ✅ Violations logged but don't fail build
  • ✅ 0 violations baseline established
  • ✅ Suppressions configured for third-party code

Next Phase

Phase 3.2: Strict Mode (After confidence)

Once you're confident (2-3 clean commits):

# Edit pom.xml
vim pom.xml

# Change lines 252-253 from:
\u003cfailsOnError\u003efalse\u003c/failsOnError\u003e
\u003cfailOnViolation\u003efalse\u003c/failOnViolation\u003e

# To:
\u003cfailsOnError\u003etrue\u003c/failsOnError\u003e
\u003cfailOnViolation\u003etrue\u003c/failOnViolation\u003e

# Commit the change
git add pom.xml
git commit -m "chore: enable Checkstyle strict mode (Phase 3 complete)"

Troubleshooting

Build is Slow

Checkstyle adds ~5-10 seconds to build time. This is normal.

To skip Checkstyle temporarily:

mvn compile -Dcheckstyle.skip=true

Too Many Violations

If a file has many violations, consider:

  1. Suppress specific checks temporarily:
\u003c!-- In suppressions.xml --\u003e
\u003csuppress checks="ImportOrder" files=".*RBACService.java"/\u003e
  1. Fix incrementally:
  • Fix imports first (easiest)
  • Then line length
  • Then indentation
  • Finally other rules
  1. Use IDE auto-format:
  • IntelliJ: Ctrl+Alt+L
  • VS Code: Shift+Alt+F

Checkstyle vs. Error Prone Conflicts

Both tools run together. If they conflict:

Error Prone takes precedence (catches bugs)
Checkstyle handles style (formatting)

Usually no conflicts because they check different things.


Reports

Console Output

Warnings appear during build:

[WARN] RBACService.java:11:1: Wrong lexicographical order for 'java.io.FileInputStream' import.

HTML Report

# Generate report
mvn checkstyle:checkstyle

# Open in browser
open target/site/checkstyle.html

The HTML report shows:

  • Files checked
  • Violations by severity
  • Violation by rule type
  • Detailed location for each issue

Integration with Git Hooks

Current: Not in Pre-commit Hook

Checkstyle is not yet in the pre-commit hook (only Error Prone is).

Future: Add to Pre-commit Hook

Once in strict mode, add to .git-hooks/pre-commit-java.sh:

# After Error Prone check
if mvn checkstyle:check -q; then
echo "✅ Checkstyle passed"
else
echo "❌ Checkstyle violations found"
exit 1
fi

Customizing Rules

Disable Specific Checks

Edit config/checkstyle/google_checks.xml:

\u003c!-- Example: Disable JavadocMethod requirement --\u003e
\u003cmodule name="JavadocMethod"\u003e
\u003cproperty name="severity" value="ignore"/\u003e
\u003c/module\u003e

Note: Try to stick with Google Style Guide. Only customize if absolutely necessary.

Adjust Line Length

\u003c!-- In google_checks.xml --\u003e
\u003cmodule name="LineLength"\u003e
\u003cproperty name="max" value="120"/\u003e \u003c!-- Default is 100 --\u003e
\u003c/module\u003e

Best Practices

Do's ✅

  1. Run Checkstyle before committing

    mvn checkstyle:check
  2. Fix style in files you're editing

    • Natural, incremental improvement
    • No mass refactoring needed
  3. Use IDE auto-format

    • IntelliJ: Configure to Google Style
    • Format on save (optional)
  4. Check HTML reports periodically

    • Identify patterns
    • Track improvement over time

Don'ts ❌

  1. Don't mass-reformat entire codebase

    • Causes huge diffs
    • Breaks git blame
    • Merge conflicts
  2. Don't disable checks arbitrarily

    • Google Style exists for good reasons
    • Consistency matters
  3. Don't ignore warnings

    • They'll become errors in strict mode
    • Fix them while editing those files

Comparison with Error Prone

ToolPurposeSeveritySpeed
Error ProneBug detectionHigh (catches bugs)Fast (~10s)
CheckstyleStyle enforcementMedium (readability)Fast (~5s)

Both run together:

  1. Error Prone checks for bugs (strict mode)
  2. Checkstyle checks for style (warning mode)
  3. Complementary, not redundant

Migration Path

Current: Phase 3.1 (WARNING mode) ← We are here

  • ✅ Checkstyle integrated
  • ✅ Running on every build
  • ✅ 0 violations baseline
  • ⚠️ Warnings logged, build succeeds

Next: Phase 3.2 (STRICT mode)

After 2-3 clean commits:

  • Enable failOnViolation=true
  • Build fails on new violations
  • Style consistency enforced

Future: Add to Pre-commit Hook

  • Checkstyle runs before commit
  • Prevents style violations from entering repo
  • Immediate feedback

Resources


Summary

Phase 3 (Checkstyle) Successfully Implemented:

  • Google Java Style Guide enforced
  • WARNING mode active (no build failures)
  • 0 violations baseline
  • Suppressions for generated/third-party code
  • Ready to graduate to strict mode

Impact:

  • Code consistency improved
  • Readability standardized
  • Foundation for strict enforcement
  • Complements Error Prone bug detection

Next: After 2-3 commits, enable strict mode! 🚀