clean-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Clean Code

Clean Code

Improve existing code so it is easier to read, safer to change, and simpler to test while preserving behavior by default.
改进现有代码,使其更易读、修改更安全、测试更简单,同时默认保留原有行为。

Operating Rules

操作规则

  • Preserve external behavior unless the user explicitly asks for a behavior change.
  • Keep public APIs, side effects, error behavior, and performance characteristics stable unless changing them is part of the request.
  • Prefer the smallest useful change over a broad rewrite.
  • Improve names before adding comments or abstractions.
  • Keep domain language visible. Do not hide business rules behind generic helpers.
  • Remove duplication only when duplicated code represents the same concept and has the same reason to change.
  • Avoid new patterns, dependencies, formatting churn, and module moves unless they clearly reduce real complexity.
  • If tests are missing and the refactor is risky, add or suggest focused characterization tests before changing structure deeply.
  • 除非用户明确要求更改行为,否则保留外部行为。
  • 保持public APIs、side effects、错误行为和性能特征稳定,除非更改它们是请求的一部分。
  • 优先选择最小的有效变更,而非大范围重写。
  • 在添加注释或抽象之前先优化命名。
  • 保留领域语言可见性,不要将业务规则隐藏在通用工具背后。
  • 仅当重复代码代表同一概念且有相同的变更理由时,才消除重复。
  • 避免引入新模式、依赖、格式变动和模块迁移,除非它们能明确降低实际复杂度。
  • 如果缺少测试且重构存在风险,在深度修改结构之前添加或建议针对性的特征测试。

Workflow

工作流程

  1. Understand the code.
    • Identify the code's purpose, public interfaces, inputs, outputs, side effects, invariants, framework constraints, and existing tests.
    • If the user asked for review only, report findings without editing.
  2. Classify the work.
    • Use
      local cleanup
      for naming, constants, simple extraction, and control-flow clarity.
    • Use
      refactor
      for behavior-preserving structural changes.
    • Use
      bug fix plus cleanup
      only when the user allowed a behavior change or the requested bug is clear.
    • Treat
      redesign
      as out of scope unless the user explicitly asked for it.
  3. Choose the smallest valuable improvements.
    • Rename unclear identifiers.
    • Extract meaningful constants for magic values.
    • Extract small helpers when they name a real step in the domain.
    • Flatten nested control flow with guard clauses.
    • Separate parsing, validation, business rules, persistence, formatting, orchestration, and side effects when they are tangled.
    • Improve error handling consistency without weakening existing errors.
    • Improve or add tests when risk justifies it.
  4. Edit safely.
    • Keep changes scoped to the requested code path.
    • Make one logical improvement at a time when possible.
    • Preserve edge cases, error messages, observable timing assumptions, and data shapes.
    • Do not replace clear code with clever code.
    • Do not over-abstract code that is merely similar rather than conceptually duplicated.
  5. Validate.
    • Run the most relevant existing tests or checks when available.
    • If tests cannot be run, say why.
    • Re-check that names express intent, functions are focused, abstraction levels are consistent, comments remain accurate, and side effects are visible.
  1. 理解代码。
    • 确定代码的用途、公共接口、输入、输出、side effects、不变量、框架约束和现有测试。
    • 如果用户仅要求审查,仅报告发现的问题而不修改代码。
  2. 对工作进行分类。
    • 命名、常量提取、简单提取和控制流清晰度优化使用
      local cleanup
    • 保留行为的结构性变更使用
      refactor
    • 仅当用户允许更改行为或明确要求修复bug时,使用
      bug fix plus cleanup
    • 除非用户明确要求,否则
      redesign
      属于超出范围的工作。
  3. 选择最小的有价值改进。
    • 重命名不清晰的标识符。
    • 为魔法值提取有意义的常量。
    • 当辅助函数能命名领域中的实际步骤时,提取小型辅助函数。
    • 使用卫语句扁平化嵌套控制流。
    • 当解析、验证、业务规则、持久化、格式化、编排和side effects相互交织时,将它们分离。
    • 在不削弱现有错误处理能力的前提下,提升错误处理的一致性。
    • 当风险较高时,改进或添加测试。
  4. 安全地修改代码。
    • 将变更范围限定在请求的代码路径内。
    • 尽可能一次只进行一项逻辑改进。
    • 保留边缘情况、错误消息、可观察的时序假设和数据结构。
    • 不要用花哨的代码替代清晰的代码。
    • 不要对仅表面相似而非概念重复的代码进行过度抽象。
  5. 验证。
    • 运行最相关的现有测试或检查(如果可用)。
    • 如果无法运行测试,说明原因。
    • 重新检查命名是否表达了意图、函数是否聚焦、抽象层级是否一致、注释是否准确以及side effects是否可见。

Smell Checklist

代码异味检查清单

Look for unclear names, long functions, mixed responsibilities, duplicated logic, deep nesting, complex booleans, flag arguments, hidden mutations, large classes, primitive obsession, data clumps, long parameter lists, inconsistent abstraction levels, noisy comments, magic values, inconsistent error handling, and brittle or missing tests.
留意不清晰的命名、过长的函数、混合的职责、重复的逻辑、深层嵌套、复杂布尔表达式、标志参数、隐藏的修改、过大的类、primitive obsession、数据聚合、过长的参数列表、不一致的抽象层级、冗余注释、魔法值、不一致的错误处理以及脆弱或缺失的测试。

Naming Guide

命名指南

  • Prefer intent-revealing names such as
    elapsedTimeInDays
    ,
    customerRepository
    ,
    isEligibleForDiscount
    ,
    calculateInvoiceTotal
    , and
    parsePaymentRequest
    .
  • Avoid vague names such as
    data
    ,
    info
    ,
    manager
    ,
    processor
    , and
    helper
    unless the domain really uses that term.
  • Name booleans so they read naturally:
    isActive
    ,
    hasPermission
    ,
    canRetry
    ,
    shouldNotifyCustomer
    .
  • Name functions with verbs when practical:
    calculateTotal
    ,
    validateRequest
    ,
    loadCustomer
    ,
    sendReceipt
    ,
    formatCurrency
    .
  • 优先选择能揭示意图的命名,例如
    elapsedTimeInDays
    customerRepository
    isEligibleForDiscount
    calculateInvoiceTotal
    parsePaymentRequest
  • 避免模糊的命名,例如
    data
    info
    manager
    processor
    helper
    ,除非领域中确实使用这些术语。
  • 布尔值命名要自然易读:
    isActive
    hasPermission
    canRetry
    shouldNotifyCustomer
  • 函数命名尽可能使用动词:
    calculateTotal
    validateRequest
    loadCustomer
    sendReceipt
    formatCurrency

Comments

注释规范

  • Keep comments that explain business rules, external constraints, security concerns, performance tradeoffs, historical context, or non-obvious decisions.
  • Remove or rewrite comments that repeat the code, explain code that should be renamed or extracted, are outdated, or add noise.
  • 保留解释业务规则、外部约束、安全顾虑、性能权衡、历史背景或非显而易见决策的注释。
  • 删除或重写重复代码内容、解释应被重命名或提取的代码、已过时或冗余的注释。

Output Contract

输出约定

When returning results, include:
  • summary
    : what was improved.
  • key_improvements
    : the most important readability, maintainability, safety, or testability changes.
  • behavior_changes
    : state
    none
    when behavior was preserved; otherwise explain exactly what changed and why.
  • validation
    : tests or checks run, with results.
  • risks
    : missing tests, unclear requirements, framework constraints, or areas needing extra review.
For review-only tasks, lead with findings ordered by severity and include file and line references where possible.
返回结果时,需包含:
  • summary
    :改进内容概述。
  • key_improvements
    :最重要的可读性、可维护性、安全性或可测试性变更。
  • behavior_changes
    :当行为被保留时填写
    none
    ;否则准确说明变更内容及原因。
  • validation
    :已运行的测试或检查及其结果。
  • risks
    :缺失的测试、不明确的需求、框架约束或需要额外审查的区域。
对于仅审查的任务,按严重性排序列出发现的问题,并尽可能包含文件和行号引用。