代码检查:让工具替你把关
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,保存代码就能看到问题:
- 安装 SonarLint 插件
- 右键项目 → SonarLint → Analyze
- 实时看到红线和警告
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总结
- 开发阶段:IDE 里装 SonarLint,实时看到问题
- 提交阶段:Git Hook 跑 pre-commit 检查
- CI 阶段:Pipeline 里跑 SpotBugs + Checkstyle
- 人工 review:工具拦不住的逻辑问题,再由人来审
工具能做的事,不要浪费人的时间。
