clean-code-zh

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

代码整洁之道 (Clean Code)

Clean Code

本技能赋能 AI Agent 编写、审查和重构符合 Robert C. Martin (Uncle Bob)《代码整洁之道》原则的代码。其核心目标是提高代码的可读性、可维护性和长期生产力。
This skill empowers AI Agents to write, review, and refactor code that adheres to the principles of Robert C. Martin (Uncle Bob)'s Clean Code. Its core goal is to improve code readability, maintainability, and long-term productivity.

核心原则

Core Principles

1. 有意义的命名

1. Meaningful Names

  • 名副其实:变量、函数或类的名称应说明其存在的意义、功能以及用法。
  • 避免误导:避免使用具有特定编程含义的词(如
    accountList
    除非它真的是
    List
    )。
  • 做有意义的区分:避免使用
    data1
    ,
    data2
    theMessage
    这样模糊的命名。
  • 使用读得出来的名称:避免使用缩写(如
    genymdhms
    ->
    generationTimestamp
    )。
  • 使用可搜索的名称:单字母变量仅限用于短小的循环内部。
  • Reveal Intention: The name of a variable, function, or class should explain why it exists, what it does, and how it is used.
  • Avoid Misleading Names: Avoid using words with specific programming meanings (e.g.,
    accountList
    unless it is actually a
    List
    ).
  • Make Meaningful Distinctions: Avoid vague names like
    data1
    ,
    data2
    , or
    theMessage
    .
  • Use Pronounceable Names: Avoid abbreviations (e.g.,
    genymdhms
    ->
    generationTimestamp
    ).
  • Use Searchable Names: Single-letter variables should only be used inside short loops.

2. 函数

2. Functions

  • 短小:函数的第一条规则是短小。第二条规则是还要更短小。
  • 只做一件事:函数应该做一件事,做好这件事,且只做这一件事。
  • 每个函数一个抽象层级:确保函数内的语句都在同一抽象层级上。
  • 函数参数:最理想的参数数量是 0,其次是 1,再次是 2。尽量避免 3 个及以上参数。
  • 无副作用:函数不应在暗地里修改全局变量或对象状态。
  • 分隔指令与询问:函数要么执行某项动作,要么回答某个问题,不应兼而有之。
  • Small: The first rule of functions is to be small. The second rule is to be even smaller.
  • Do One Thing: A function should do one thing, do it well, and only do that one thing.
  • One Level of Abstraction per Function: Ensure all statements within a function are at the same level of abstraction.
  • Function Arguments: The ideal number of arguments is zero, followed by one, then two. Avoid three or more arguments as much as possible.
  • No Side Effects: Functions should not secretly modify global variables or object states.
  • Separate Commands from Queries: A function should either perform an action or answer a question, not both.

3. 注释

3. Comments

  • 注释不能美化糟糕的代码:代码应当能自解释。如果需要注释,首先考虑是否可以通过重构来消除注释。
  • 好的注释:法律信息、对意图的解释、警示后果、TODO 注释。
  • 糟糕的注释:喃喃自语、冗余注释、误导性注释、日志式注释、署名注释、废话注释。
  • Comments Cannot Rescue Bad Code: Code should be self-explanatory. If comments are needed, first consider whether refactoring can eliminate the need for them.
  • Good Comments: Legal information, explanations of intent, warnings of consequences, TODO comments.
  • Bad Comments: Rambling, redundant comments, misleading comments, log-style comments, signature comments, meaningless comments.

4. 格式

4. Formatting

  • 垂直距离:关系密切的概念应在垂直方向上靠近。
  • 横向格式:代码行不应过宽(建议限制在 100-120 字符以内)。
  • 团队规则:始终遵循团队约定的格式规范。
  • Vertical Distance: Closely related concepts should be vertically close to each other.
  • Horizontal Formatting: Code lines should not be too wide (recommended limit of 100-120 characters).
  • Team Rules: Always follow the formatting conventions agreed upon by the team.

5. 错误处理

5. Error Handling

  • 使用异常而非返回码:返回码会导致调用者逻辑混乱。
  • 先写 Try-Catch-Finally 语句:这有助于定义程序的范围。
  • 不要返回 null:返回空集合或抛出异常,以避免到处都是空检查。
  • 不要传递 null:除非 API 明确要求,否则禁止向函数传递 null。
  • Use Exceptions Rather Than Return Codes: Return codes can lead to messy caller logic.
  • Write Try-Catch-Finally First: This helps define the scope of the program.
  • Don’t Return Null: Return an empty collection or throw an exception to avoid null checks everywhere.
  • Don’t Pass Null: Unless explicitly required by the API, never pass null to a function.

6. 类

6. Classes

  • 单一权责原则 (SRP):一个类应该只有一个导致其变化的原因。
  • 内聚性:类应该只有少量的实体变量,方法应操作这些变量。
  • 为了修改而组织:类应该对扩展开放,对修改关闭 (OCP)。
  • Single Responsibility Principle (SRP): A class should have only one reason to change.
  • Cohesion: A class should have a small number of instance variables, and methods should operate on these variables.
  • Organize for Change: Classes should be open for extension but closed for modification (OCP).

何时使用 (When to Use)

When to Use

  • 编写新功能:确保初始实现符合整洁标准。
  • 代码审查 (Code Review):识别违反整洁原则的模式。
  • 技术债重构:将“能跑就行”的代码转化为专业级代码。
  • API 设计:创建直观且自解释的接口。
  • Writing New Features: Ensure the initial implementation meets clean code standards.
  • Code Review: Identify patterns that violate clean code principles.
  • Technical Debt Refactoring: Convert "it works" code into professional-grade code.
  • API Design: Create intuitive and self-explanatory interfaces.

审查清单 (Review Checklist)

Review Checklist

  1. 名称是否表达了意图?
  2. 函数是否超过了 20 行?
  3. 函数是否混合了多个抽象层级?
  4. 是否可以通过重命名变量来消除某段注释?
  5. 是否使用了异常处理而非 if/else 返回错误码?
  6. 类是否过于庞大(违反 SRP)?
  1. Does the name express its intention?
  2. Is the function longer than 20 lines?
  3. Does the function mix multiple levels of abstraction?
  4. Can a comment be eliminated by renaming a variable?
  5. Is exception handling used instead of if/else return error codes?
  6. Is the class too large (violates SRP)?