← Writing

Improving AI-generated Java code with Checkstyle, Qodana, and SonarQube

On this page

Suppose an AI refactors a shipping fee calculation and changes >= 50_000 to > 50_000. Both versions can compile and pass style checks. At exactly 50,000 won, however, the order no longer qualifies for free shipping. Use tests to protect the business rule and linting and static analysis to catch issues that are easy to miss in review. When you ask AI to fix a failure, give it the failed check and the behavior it must preserve.

Decide what each tool checks

Tool What it checks When to run it
Checkstyle Team Java conventions, such as imports and naming Locally and in PRs
PMD Selected Java static analysis rules, such as unnecessary branches and unused code Locally and in PRs
Qodana Code smells and potential defects using JetBrains inspection profiles Locally and in PRs. Review new findings against a baseline
SonarQube Community Build Project health, including maintainability, duplication, and coverage, with a quality gate Main branch analysis
JUnit and JaCoCo JUnit verifies business rules and JaCoCo records which code tests exercise Locally and in PRs. SonarQube can import JaCoCo XML

Checkstyle and PMD are open source. The Qodana Community linters are subject to separate JetBrains terms. SonarQube Community Build itself uses LGPLv3, and the bundled analyzers use Sonar Source-Available License v1.0. If your team requires open-source licenses, you can start with Checkstyle, PMD, JUnit, and JaCoCo. Checkstyle license, PMD license, Qodana Community terms, Sonar licensing

1. Test the business rule before asking AI to refactor

Shipping is free for orders of at least 50,000 won and costs 3,000 won below that amount. Choose an order amount on each side of the boundary and one at the boundary.

Order amount Expected shipping fee
49,999 won 3,000 won
50,000 won 0 won
50,001 won 0 won

The shipping fee is zero for orders of at least 50,000 won and 3,000 won for orders below that amount

This example compares only the order amount. See refactoring a shipping fee calculation for a version with membership and a remote-area surcharge.

Save the code below as ShippingFeeCheck.java. The main method compares the returned fees with the three expected values in the table.

public class ShippingFeeCheck {
    static int shippingFee(long orderWon) {
        return orderWon >= 50_000L ? 0 : 3_000;
    }

    public static void main(String[] args) {
        long[] orders = {49_999L, 50_000L, 50_001L};
        int[] expectedFees = {3_000, 0, 0};
        for (int index = 0; index < orders.length; index++) {
            int actualFee = shippingFee(orders[index]);
            if (actualFee != expectedFees[index]) {
                throw new AssertionError(
                    "orderWon=%d, expected=%d, actual=%d"
                        .formatted(orders[index], expectedFees[index], actualFee)
                );
            }
        }
        System.out.println("All 3 shipping fees matched.");
    }
}
java ShippingFeeCheck.java

All three values matched on Java 21.0.1.

All 3 shipping fees matched.

A copy with only the comparison operator changed from >= to > failed at 50,000 won. Here is the first line of the exception.

Exception in thread "main" java.lang.AssertionError: orderWon=50000, expected=0, actual=3000

In a project, put these three inputs in a parameterized JUnit test to enforce the same rule. The run above used Java’s single-file launcher. It did not exercise JUnit or CI.

2. Run the same checks locally and in pull requests

If your project uses Maven Wrapper and configures Checkstyle and tests in pom.xml, run the following commands locally and in PRs. If you bind Checkstyle to Maven’s verify phase, ./mvnw verify is enough. Maven Checkstyle Plugin

./mvnw checkstyle:check
./mvnw verify

For a project with many existing warnings, scan main first and save its SARIF result as a baseline file. Qodana Cloud enables a baseline by default. Passing a file explicitly overrides those settings. The documented default path is .qodana/baseline.sarif.json.

Use the same linter version and profile in PRs. Run the example from the project root with Qodana CLI and the project JDK installed and the baseline file in place. With a baseline, --fail-threshold 0 counts all findings that Qodana cannot match to it. A single new finding fails the scan. Baseline, CLI options, Quality gate

qodana scan \
  --linter qodana-jvm-community \
  --within-docker false \
  --baseline .qodana/baseline.sarif.json \
  --fail-threshold 0

Start by reviewing reports with the quality gate disabled. Make the check required once you can distinguish issues worth fixing from false positives. If PMD and Qodana flag the same issue, decide which check will enforce it at merge time. For example, Checkstyle can enforce coding conventions while you review duplication or unnecessary branches in the Qodana report.

3. Track main branch quality in SonarQube

With Community Build, run the Maven build and Sonar analysis after merging into main. Have the build generate JaCoCo XML first and configure SonarScanner to import it. The quality gate can then use metrics such as coverage and duplication on new code. Use sonar.qualitygate.wait=true to make CI wait for the gate result. A failure at this stage reflects the state of the main branch after the merge. Before merging, use the tests, lint checks, and Qodana scan above. SonarQube Server offers native PR analysis starting with Developer Edition. Main branch analysis, Java coverage, Community Build CI integration, Server PR analysis

4. Give AI the failure and ask for a small fix

Give the AI the failed check, the relevant diff, and the business rule it must preserve. From SARIF or CI logs, extract the check name, file location, and expected and actual values.

This PR should make the shipping fee calculation easier to read.

Rules to preserve
- Shipping costs 3,000 won for an order of 49,999 won.
- Shipping costs 0 won for orders of 50,000 and 50,001 won.

Failure log and relevant diff
[Paste the file and line number, check name, expected and actual values, and relevant diff.]

First, explain with evidence whether the failure is a business rule violation,
a static analysis warning, or an issue that needs further investigation.
Change only the relevant code and keep existing test expectations and check settings.
List the commands you ran after the change and report their actual results.
Identify any checks you could not run and explain why.

In PR review, rerun the same commands. Check that the previously failing check and existing tests pass, and that the diff stays confined to the issue.

The boundary and failure reproduced on Java 21.0.1. The Maven, Qodana, and SonarQube settings were checked against their official documentation. The full CI pipeline described in the example was outside the execution scope.

Discussion

View on GitHub ↗