ErrorProne 導入指引

導入效應

效應 說明
Compile-time Bug 偵測 在編譯期攔截空指標、字串比較、資源外洩等問題
比 Checkstyle 更強 不只格式檢查,而是語意層級的錯誤分析
Google 級品質標準 Google 內部使用的品質工具,規則經過大規模驗證
AI 低級錯誤防護 AI 常犯的 == 比字串、Optional.get() 等錯誤直接擋下
零 Runtime Cost 所有檢查都在編譯期,不影響程式效能
自動修復 部分 Bug 提供自動修復,可搭配 OpenRewrite

1. Maven 導入

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.13.0</version>
    <configuration>
        <compilerArgs>
            <arg>-Xplugin:ErrorProne</arg>
            <arg>-Xep:ConstantCaseForConstants:ERROR</arg>
        </compilerArgs>
        <annotationProcessorPaths>
            <path>
                <groupId>com.google.errorprone</groupId>
                <artifactId>error_prone_core</artifactId>
                <version>2.35.1</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

2. Gradle 導入

dependencies {
    errorprone 'com.google.errorprone:error_prone_core:2.35.1'
}

tasks.withType(JavaCompile).configureEach {
    options.errorprone {
        error("SelfEquals", "FallThrough", "MissingSummary")
        warn("DefaultCharset", "StringSplitter")
        disable("GeneralTypeNameCheck")  // 關閉不需要的檢查
    }
}

3. 常見檢查規則

3.1 字串比較

// ❌ AI 常犯
if (str1 == str2) { ... }

// ✅ ErrorProne 改為
if (str1.equals(str2)) { ... }

3.2 Optional 濫用

// ❌ AI 常犯
Optional<User> user = findUser(id);
User u = user.get();  // 可能 NoSuchElementException

// ✅ ErrorProne 建議
User u = user.orElseThrow(() -> new UserNotFoundException(id));

3.3 資源外洩

// ❌ AI 常犯
InputStream is = new FileInputStream(file);
// 忘記 close

// ✅ ErrorProne + Try-with-resources
try (InputStream is = new FileInputStream(file)) {
    // ...
}

3.4 Fall-through

// ❌ AI 常犯
switch (status) {
    case ACTIVE:
        doActive();
        // 忘記 break,fall-through
    case INACTIVE:
        doInactive();
        break;
}

// ✅ ErrorProne 警告
switch (status) {
    case ACTIVE:
        doActive();
        break;
    case INACTIVE:
        doInactive();
        break;
}

4. 常用 ErrorProne Checks

Check Level 說明
SelfEquals ERROR x.equals(x) 永遠 true
FallThrough ERROR switch 沒有 break
MissingSummary WARNING Javadoc 缺少摘要
DefaultCharset WARNING 使用平台預設編碼
StringSplitter WARNING split() 沒有 regex
ImmutableEnumChecker ERROR Enum 有可變欄位
MissingOverride ERROR 繒承方法沒加 @Override
ReturnValueIgnored WARNING 忽略回傳值

5. CI 整合

# azure-pipelines.yml
- stage: CompileCheck
  jobs:
    - job: ErrorProne
      steps:
        - task: Maven@4
          inputs:
            goals: 'compile'
            options: '-Xep-all-errors-as-warnings'
        - task: Maven@4
          inputs:
            goals: 'test'

6. 禁用特定 Check

<!-- 專案不適用時可關閉 -->
<arg>-Xep:DefaultCharset:OFF</arg>
<arg>-Xep:FutureReturn:OFF</arg>

7. 與其他工具搭配

ErrorProne (編譯期)
    ↓
Semgrep (靜態分析)
    ↓
SonarQube (全面掃描)

8. 參考資源