代码审查
一句话解释
代码审查是合并前的同行审查——捕获 bug、提高质量、分享知识、执行标准。
用大白话说
代码审查是让其他开发者在代码合并前审查的做法。它是软件开发中最有效的质量保证实践之一。代码审查捕获什么:1. Bug——逻辑错误、边界情况、竞态条件
- 安全问题——注入漏洞、认证缺陷
- 性能——低效算法、N+1 查询
- 可读性——不清晰命名、复杂逻辑、缺失注释
- 标准——风格违规、模式不一致
- 测试覆盖——缺失测试、不充分断言
- 设计——紧耦合、缺失抽象、API 设计代码审查流程:1. 作者创建含变更的 PR/MR
- 审查者检查差异,留评论
- 作者处理反馈,推送更新
- 审查者批准 → 合并;或要求修改 → 迭代最佳实践:
- 小 PR——一次审查 200-400 行(超出质量下降)
- 具体反馈——指出问题,建议修复
- 友善语气——批评代码,不批评人
- 提问——「为什么这个方法?」教学并揭示问题
- 完成时批准——不要让 PR 悬而未决工具:GitHub PR、GitLab MR、Gerrit、Crucible。
示例
text
Code Review Checklist
====================
Functionality:
[ ] Does the code do what the PR description says?
[ ] Are edge cases handled? (null, empty, max, min)
[ ] Are error cases handled gracefully?
Tests:
[ ] Are there tests for the new code?
[ ] Do tests cover happy path AND error cases?
[ ] Are assertions meaningful (not just "doesn't throw")?
Security:
[ ] Is user input validated and sanitized?
[ ] Are there any hardcoded secrets/credentials?
[ ] Are auth checks in place?
Performance:
[ ] Any N+1 query patterns?
[ ] Any unnecessary loops or allocations?
[ ] Is the algorithm complexity acceptable?
Readability:
[ ] Are names clear and consistent?
[ ] Is complex logic explained?
[ ] Could this be simpler?
Design:
[ ] Does this change fit the existing architecture?
[ ] Is the code properly separated (single responsibility)?
[ ] Are the public APIs well-designed?代码审查清单确保一致质量。审查者检查功能、测试、安全、性能、可读性和设计。小而聚焦的 PR 使审查更有效。
常见混淆
容易混淆的对象: static analysis
关键区别: 代码审查是人工同行审查——捕获设计问题、逻辑错误、分享知识,但主观且受人类注意力限制。静态分析是自动化工具分析——确定性地捕获风格违规、类型错误和已知模式,但无法理解意图或设计。代码审查和静态分析互补——都用。
相关术语
相关资源
相关课程
- Code Quality
代码审查。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。