Skip to content

代码检查:让工具替你把关

review 时你最怕看到什么?

java
if (list != null && list.size() > 0) { ... } // 手写的判空
if (str.indexOf("a") >= 0) { ... }             // 过时的写法

这些问题,工具早就知道了。代码检查就是让机器替你做第一轮 review,把低级错误拦在 CI 里。

三大检查工具

SpotBugs:找 Bug

SpotBugs 通过静态分析字节码来发现问题,不只是风格问题,而是真正的 Bug:

bash
# Maven 集成
mvn spotbugs:check

# 查看详细报告
mvn spotbugs:gui

常见检测项:

检测项问题建议
DMI直接用 new Date()Instant.now()
NP可能 NPE增加判空
IL集合遍历中删除用 Iterator
SI静态字段引用可变集合防御性拷贝

Checkstyle:守风格

Checkstyle 检查代码风格——命名、缩进、空格、注释。团队风格统一的利器:

bash
mvn checkstyle:check

规则配置示例:

xml
<rule key="ConstantName">
    <properties>
        <property name="format" value="^[A-Z][A-Z0-9]*$"/>
    </properties>
</rule>
<rule key="LocalVariableName">
    <properties>
        <property name="format" value="^[a-z][a-zA-Z0-9]*$"/>
    </properties>
</rule>

SonarLint:IDE 里的实时审查

在 IDEA 里装 SonarLint,保存代码就能看到问题:

  1. 安装 SonarLint 插件
  2. 右键项目 → SonarLint → Analyze
  3. 实时看到红线和警告

Maven 配置示例

把三个工具串起来:

xml
<build>
    <plugins>
        <!-- SpotBugs -->
        <plugin>
            <groupId>com.github.spotbugs</groupId>
            <artifactId>spotbugs-maven-plugin</artifactId>
            <configuration>
                <effort>Max</effort>
                <threshold>Low</threshold>
            </configuration>
        </plugin>

        <!-- Checkstyle -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-checkstyle-plugin</artifactId>
            <configuration>
                <configLocation>checkstyle.xml</configLocation>
            </configuration>
        </plugin>
    </plugins>
</build>

常见检查项

检查项错误示例正确做法
空指针list.size() 不判空CollectionUtils.isNotEmpty(list)
资源泄漏new FileInputStream 无 close用 try-with-resources
线程安全SimpleDateFormat 多线程用DateTimeFormatter
性能String 用 + 拼接循环StringBuilder

CI 集成

把检查加到 CI pipeline,代码有问题的 MR 不让 merge:

yaml
# .gitlab-ci.yml 示例
spotbugs:
  script:
    - mvn spotbugs:check
  allow_failure: false

checkstyle:
  script:
    - mvn checkstyle:check
  allow_failure: false

总结

  1. 开发阶段:IDE 里装 SonarLint,实时看到问题
  2. 提交阶段:Git Hook 跑 pre-commit 检查
  3. CI 阶段:Pipeline 里跑 SpotBugs + Checkstyle
  4. 人工 review:工具拦不住的逻辑问题,再由人来审

工具能做的事,不要浪费人的时间。

基于 VitePress 构建