code-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Review

代码审查

When to use this skill

何时使用该技能

  • Reviewing pull requests
  • Checking code quality
  • Providing feedback on implementations
  • Identifying potential bugs
  • Suggesting improvements
  • Security audits
  • Performance analysis
  • 审查拉取请求(PR)
  • 检查代码质量
  • 针对实现方案提供反馈
  • 识别潜在漏洞
  • 提出优化建议
  • 安全审计
  • 性能分析

Instructions

操作指南

Step 1: Understand the context

步骤1:了解上下文

Read the PR description:
  • What is the goal of this change?
  • Which issues does it address?
  • Are there any special considerations?
Check the scope:
  • How many files changed?
  • What type of changes? (feature, bugfix, refactor)
  • Are tests included?
阅读PR描述:
  • 本次变更的目标是什么?
  • 解决了哪些问题?
  • 是否有特殊注意事项?
检查变更范围:
  • 有多少文件被修改?
  • 变更类型是什么?(功能新增、Bug修复、代码重构)
  • 是否包含测试代码?

Step 2: High-level review

步骤2:高层级审查

Architecture and design:
  • Does the approach make sense?
  • Is it consistent with existing patterns?
  • Are there simpler alternatives?
  • Is the code in the right place?
Code organization:
  • Clear separation of concerns?
  • Appropriate abstraction levels?
  • Logical file/folder structure?
架构与设计:
  • 该实现方案是否合理?
  • 是否与现有代码模式保持一致?
  • 是否存在更简洁的替代方案?
  • 代码放置的位置是否恰当?
代码组织结构:
  • 是否清晰分离关注点?
  • 抽象层级是否合适?
  • 文件/文件夹结构是否符合逻辑?

Step 3: Detailed code review

步骤3:细节代码审查

Naming:
  • Variables: descriptive, meaningful names
  • Functions: verb-based, clear purpose
  • Classes: noun-based, single responsibility
  • Constants: UPPER_CASE for true constants
  • Avoid abbreviations unless widely known
Functions:
  • Single responsibility
  • Reasonable length (< 50 lines ideally)
  • Clear inputs and outputs
  • Minimal side effects
  • Proper error handling
Classes and objects:
  • Single responsibility principle
  • Open/closed principle
  • Liskov substitution principle
  • Interface segregation
  • Dependency inversion
Error handling:
  • All errors caught and handled
  • Meaningful error messages
  • Proper logging
  • No silent failures
  • User-friendly errors for UI
Code quality:
  • No code duplication (DRY)
  • No dead code
  • No commented-out code
  • No magic numbers
  • Consistent formatting
命名规范:
  • 变量:名称具有描述性、表意明确
  • 函数:以动词开头,用途清晰
  • 类:以名词开头,遵循单一职责
  • 常量:真正的常量使用大写命名
  • 避免使用缩写,除非是广泛认知的缩写
函数规范:
  • 遵循单一职责原则
  • 代码长度合理(理想情况下少于50行)
  • 输入输出清晰明确
  • 副作用最小化
  • 错误处理恰当
类与对象规范:
  • 单一职责原则
  • 开闭原则
  • 里氏替换原则
  • 接口隔离原则
  • 依赖倒置原则
错误处理:
  • 所有错误均被捕获并处理
  • 错误消息表意明确
  • 日志记录恰当
  • 无静默失败情况
  • 面向UI的错误提示对用户友好
代码质量:
  • 无代码重复(遵循DRY原则)
  • 无死代码
  • 无被注释掉的代码
  • 无魔法数字
  • 代码格式一致

Step 4: Security review

步骤4:安全审查

Input validation:
  • All user inputs validated
  • Type checking
  • Range checking
  • Format validation
Authentication & Authorization:
  • Proper authentication checks
  • Authorization for sensitive operations
  • Session management
  • Password handling (hashing, salting)
Data protection:
  • No hardcoded secrets
  • Sensitive data encrypted
  • SQL injection prevention
  • XSS prevention
  • CSRF protection
Dependencies:
  • No vulnerable packages
  • Dependencies up-to-date
  • Minimal dependency usage
输入验证:
  • 所有用户输入均经过验证
  • 类型检查
  • 范围检查
  • 格式验证
认证与授权:
  • 认证检查恰当
  • 敏感操作需授权
  • 会话管理规范
  • 密码处理(哈希、加盐)
数据保护:
  • 无硬编码密钥
  • 敏感数据已加密
  • 防止SQL注入
  • 防止XSS攻击
  • 防止CSRF攻击
依赖项:
  • 无存在漏洞的包
  • 依赖项已更新至最新版本
  • 依赖项使用最小化

Step 5: Performance review

步骤5:性能审查

Algorithms:
  • Appropriate algorithm choice
  • Reasonable time complexity
  • Reasonable space complexity
  • No unnecessary loops
Database:
  • Efficient queries
  • Proper indexing
  • N+1 query prevention
  • Connection pooling
Caching:
  • Appropriate caching strategy
  • Cache invalidation handled
  • Memory usage reasonable
Resource management:
  • Files properly closed
  • Connections released
  • Memory leaks prevented
算法:
  • 算法选择恰当
  • 时间复杂度合理
  • 空间复杂度合理
  • 无不必要的循环
数据库:
  • 查询语句高效
  • 索引设置恰当
  • 防止N+1查询问题
  • 连接池配置合理
缓存:
  • 缓存策略恰当
  • 缓存失效处理到位
  • 内存使用合理
资源管理:
  • 文件已正确关闭
  • 连接已释放
  • 防止内存泄漏

Step 6: Testing review

步骤6:测试审查

Test coverage:
  • Unit tests for new code
  • Integration tests if needed
  • Edge cases covered
  • Error cases tested
Test quality:
  • Tests are readable
  • Tests are maintainable
  • Tests are deterministic
  • No test interdependencies
  • Proper test data setup/teardown
Test naming:
python
undefined
测试覆盖:
  • 新增代码包含单元测试
  • 必要时包含集成测试
  • 覆盖边缘场景
  • 错误场景已测试
测试质量:
  • 测试代码可读性强
  • 测试代码易于维护
  • 测试结果可复现
  • 测试之间无依赖
  • 测试数据的准备/清理恰当
测试命名:
python
undefined

Good

Good

def test_user_creation_with_valid_data_succeeds(): pass
def test_user_creation_with_valid_data_succeeds(): pass

Bad

Bad

def test1(): pass
undefined
def test1(): pass
undefined

Step 7: Documentation review

步骤7:文档审查

Code comments:
  • Complex logic explained
  • No obvious comments
  • TODOs have tickets
  • Comments are accurate
Function documentation:
python
def calculate_total(items: List[Item], tax_rate: float) -> Decimal:
    """
    Calculate the total price including tax.

    Args:
        items: List of items to calculate total for
        tax_rate: Tax rate as decimal (e.g., 0.1 for 10%)

    Returns:
        Total price including tax

    Raises:
        ValueError: If tax_rate is negative
    """
    pass
README/docs:
  • README updated if needed
  • API docs updated
  • Migration guide if breaking changes
代码注释:
  • 复杂逻辑已添加注释说明
  • 无冗余注释
  • TODO注释关联对应工单
  • 注释内容准确
函数文档:
python
def calculate_total(items: List[Item], tax_rate: float) -> Decimal:
    """
    Calculate the total price including tax.

    Args:
        items: List of items to calculate total for
        tax_rate: Tax rate as decimal (e.g., 0.1 for 10%)

    Returns:
        Total price including tax

    Raises:
        ValueError: If tax_rate is negative
    """
    pass
README/文档:
  • 必要时已更新README
  • API文档已更新
  • 若存在破坏性变更,已提供迁移指南

Step 8: Provide feedback

步骤8:提供反馈

Be constructive:
✅ Good:
"Consider extracting this logic into a separate function for better
testability and reusability:

def validate_email(email: str) -> bool:
    return '@' in email and '.' in email.split('@')[1]

This would make it easier to test and reuse across the codebase."

❌ Bad:
"This is wrong. Rewrite it."
Be specific:
✅ Good:
"On line 45, this query could cause N+1 problem. Consider using
.select_related('author') to fetch related objects in a single query."

❌ Bad:
"Performance issues here."
Prioritize issues:
  • 🔴 Critical: Security, data loss, major bugs
  • 🟡 Important: Performance, maintainability
  • 🟢 Nice-to-have: Style, minor improvements
Acknowledge good work:
"Nice use of the strategy pattern here! This makes it easy to add
new payment methods in the future."
保持建设性:
✅ 良好示例:
"建议将此逻辑提取为独立函数,以提升可测试性与复用性:

def validate_email(email: str) -> bool:
    return '@' in email and '.' in email.split('@')[1]

这样能更方便地进行测试,并在代码库中复用。"

❌ 不良示例:
"这部分写得不对,重写。"
保持具体:
✅ 良好示例:
"第45行的查询语句可能会导致N+1问题,建议使用
.select_related('author') 在单次查询中获取关联对象。"

❌ 不良示例:
"这里有性能问题。"
问题优先级划分:
  • 🔴 严重:安全问题、数据丢失、重大Bug
  • 🟡 重要:性能问题、可维护性问题
  • 🟢 优化项:代码风格、小改进
认可优秀工作:
"这里很好地运用了策略模式!未来添加新的支付方式会非常便捷。"

Review checklist

审查检查清单

Functionality

功能

  • Code does what it's supposed to do
  • Edge cases handled
  • Error cases handled
  • No obvious bugs
  • 代码实现了预期功能
  • 边缘场景已处理
  • 错误场景已处理
  • 无明显Bug

Code Quality

代码质量

  • Clear, descriptive naming
  • Functions are small and focused
  • No code duplication
  • Consistent with codebase style
  • No code smells
  • 命名清晰、具有描述性
  • 函数小巧且聚焦单一职责
  • 无代码重复
  • 与代码库风格保持一致
  • 无代码异味

Security

安全

  • Input validation
  • No hardcoded secrets
  • Authentication/authorization
  • No SQL injection vulnerabilities
  • No XSS vulnerabilities
  • 输入已验证
  • 无硬编码密钥
  • 认证/授权机制完善
  • 无SQL注入漏洞
  • 无XSS漏洞

Performance

性能

  • No obvious bottlenecks
  • Efficient algorithms
  • Proper database queries
  • Resource management
  • 无明显性能瓶颈
  • 算法高效
  • 数据库查询恰当
  • 资源管理规范

Testing

测试

  • Tests included
  • Good test coverage
  • Tests are maintainable
  • Edge cases tested
  • 包含测试代码
  • 测试覆盖良好
  • 测试代码易于维护
  • 边缘场景已测试

Documentation

文档

  • Code is self-documenting
  • Comments where needed
  • Docs updated
  • Breaking changes documented
  • 代码具备自解释性
  • 必要处添加了注释
  • 文档已更新
  • 破坏性变更已记录

Common issues

常见问题

Anti-patterns

反模式

God class:
python
undefined
上帝类:
python
undefined

Bad: One class doing everything

Bad: One class doing everything

class UserManager: def create_user(self): pass def send_email(self): pass def process_payment(self): pass def generate_report(self): pass

**Magic numbers**:
```python
class UserManager: def create_user(self): pass def send_email(self): pass def process_payment(self): pass def generate_report(self): pass

**魔法数字**:
```python

Bad

Bad

if user.age > 18: pass
if user.age > 18: pass

Good

Good

MINIMUM_AGE = 18 if user.age > MINIMUM_AGE: pass

**Deep nesting**:
```python
MINIMUM_AGE = 18 if user.age > MINIMUM_AGE: pass

**深层嵌套**:
```python

Bad

Bad

if condition1: if condition2: if condition3: if condition4: # deeply nested code
if condition1: if condition2: if condition3: if condition4: # deeply nested code

Good (early returns)

Good (early returns)

if not condition1: return if not condition2: return if not condition3: return if not condition4: return
if not condition1: return if not condition2: return if not condition3: return if not condition4: return

flat code

flat code

undefined
undefined

Security vulnerabilities

安全漏洞

SQL Injection:
python
undefined
SQL Injection:
python
undefined

Bad

Bad

query = f"SELECT * FROM users WHERE id = {user_id}"
query = f"SELECT * FROM users WHERE id = {user_id}"

Good

Good

query = "SELECT * FROM users WHERE id = %s" cursor.execute(query, (user_id,))

**XSS**:
```javascript
// Bad
element.innerHTML = userInput;

// Good
element.textContent = userInput;
Hardcoded secrets:
python
undefined
query = "SELECT * FROM users WHERE id = %s" cursor.execute(query, (user_id,))

**XSS**:
```javascript
// Bad
element.innerHTML = userInput;

// Good
element.textContent = userInput;
Hardcoded secrets:
python
undefined

Bad

Bad

API_KEY = "sk-1234567890abcdef"
API_KEY = "sk-1234567890abcdef"

Good

Good

API_KEY = os.environ.get("API_KEY")
undefined
API_KEY = os.environ.get("API_KEY")
undefined

Best practices

最佳实践

  1. Review promptly: Don't make authors wait
  2. Be respectful: Focus on code, not the person
  3. Explain why: Don't just say what's wrong
  4. Suggest alternatives: Show better approaches
  5. Use examples: Code examples clarify feedback
  6. Pick your battles: Focus on important issues
  7. Acknowledge good work: Positive feedback matters
  8. Review your own code first: Catch obvious issues
  9. Use automated tools: Let tools catch style issues
  10. Be consistent: Apply same standards to all code
  1. 及时审查:不要让提交者等待
  2. 保持尊重:聚焦代码而非个人
  3. 说明原因:不要只指出问题,还要解释为什么
  4. 提供替代方案:展示更优实现方式
  5. 使用示例:代码示例能让反馈更清晰
  6. 抓重点:聚焦重要问题
  7. 认可优秀工作:积极反馈同样重要
  8. 先自查代码:提前发现明显问题
  9. 使用自动化工具:让工具处理代码风格问题
  10. 保持一致:对所有代码应用相同标准

Tools to use

推荐工具

Linters:
  • Python: pylint, flake8, black
  • JavaScript: eslint, prettier
  • Go: golint, gofmt
  • Rust: clippy, rustfmt
Security:
  • Bandit (Python)
  • npm audit (Node.js)
  • OWASP Dependency-Check
Code quality:
  • SonarQube
  • CodeClimate
  • Codacy
代码检查工具(Linters):
  • Python: pylint, flake8, black
  • JavaScript: eslint, prettier
  • Go: golint, gofmt
  • Rust: clippy, rustfmt
安全工具:
  • Bandit (Python)
  • npm audit (Node.js)
  • OWASP Dependency-Check
代码质量工具:
  • SonarQube
  • CodeClimate
  • Codacy

References

参考资料

Examples

示例

Example 1: Basic usage

示例1:基础用法

<!-- Add example content here -->
<!-- Add example content here -->

Example 2: Advanced usage

示例2:高级用法

<!-- Add advanced example content here -->
<!-- Add advanced example content here -->