clean-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Clean Code Skill

Clean Code Skill

This skill embodies the principles of "Clean Code" by Robert C. Martin (Uncle Bob). Use it to transform "code that works" into "code that is clean."
该技能遵循Robert C. Martin(鲍勃大叔)所著《Clean Code》中的原则,可将“能运行的代码”转化为“整洁的代码”。

🧠 Core Philosophy

🧠 核心理念

"Code is clean if it can be read, and enhanced by a developer other than its original author." — Grady Booch
“如果代码能被原作者之外的开发者阅读和改进,那它就是整洁的。”——Grady Booch

When to Use

使用场景

Use this skill when:
  • Writing new code: To ensure high quality from the start.
  • Reviewing Pull Requests: To provide constructive, principle-based feedback.
  • Refactoring legacy code: To identify and remove code smells.
  • Improving team standards: To align on industry-standard best practices.
在以下场景中使用该技能:
  • 编写新代码:从一开始就确保代码高质量。
  • 评审Pull Requests:提供基于原则的建设性反馈。
  • 重构遗留代码:识别并消除代码异味。
  • 提升团队标准:统一行业标准最佳实践。

1. Meaningful Names

1. 有意义的命名

  • Use Intention-Revealing Names:
    elapsedTimeInDays
    instead of
    d
    .
  • Avoid Disinformation: Don't use
    accountList
    if it's actually a
    Map
    .
  • Make Meaningful Distinctions: Avoid
    ProductData
    vs
    ProductInfo
    .
  • Use Pronounceable/Searchable Names: Avoid
    genymdhms
    .
  • Class Names: Use nouns (
    Customer
    ,
    WikiPage
    ). Avoid
    Manager
    ,
    Data
    .
  • Method Names: Use verbs (
    postPayment
    ,
    deletePage
    ).
  • 使用能揭示意图的名称:使用
    elapsedTimeInDays
    而非
    d
  • 避免误导性命名:如果实际是
    Map
    ,就不要使用
    accountList
  • 明确区分名称:避免使用
    ProductData
    ProductInfo
    这类模糊的区分。
  • 使用易读/易搜索的名称:避免
    genymdhms
    这类缩写。
  • 类名:使用名词(如
    Customer
    WikiPage
    ),避免
    Manager
    Data
    这类宽泛的名称。
  • 方法名:使用动词(如
    postPayment
    deletePage
    )。

2. Functions

2. 函数

  • Small!: Functions should be shorter than you think.
  • Do One Thing: A function should do only one thing, and do it well.
  • One Level of Abstraction: Don't mix high-level business logic with low-level details (like regex).
  • Descriptive Names:
    isPasswordValid
    is better than
    check
    .
  • Arguments: 0 is ideal, 1-2 is okay, 3+ requires a very strong justification.
  • No Side Effects: Functions shouldn't secretly change global state.
  • 短小!:函数应该比你想象的更短。
  • 单一职责:一个函数只做一件事,并且做好这件事。
  • 单一抽象层级:不要将高层业务逻辑与底层细节(如正则表达式)混合。
  • 描述性名称
    isPasswordValid
    check
    更清晰。
  • 参数:0个参数是理想状态,1-2个可以接受,3个及以上需要充分的理由。
  • 无副作用:函数不应偷偷修改全局状态。

3. Comments

3. 注释

  • Don't Comment Bad Code—Rewrite It: Most comments are a sign of failure to express ourselves in code.
  • Explain Yourself in Code:
    python
    # Check if employee is eligible for full benefits
    if employee.flags & HOURLY and employee.age > 65:
    vs
    python
    if employee.isEligibleForFullBenefits():
  • Good Comments: Legal, Informative (regex intent), Clarification (external libraries), TODOs.
  • Bad Comments: Mumbling, Redundant, Misleading, Mandated, Noise, Position Markers.
  • 不要为糟糕的代码写注释——重写它:大多数注释都表明我们未能用代码清晰表达意图。
  • 用代码自我解释:
    python
    # 检查员工是否符合全额福利资格
    if employee.flags & HOURLY and employee.age > 65:
    vs
    python
    if employee.isEligibleForFullBenefits():
  • 好的注释:法律相关注释、说明性注释(如正则表达式的意图)、澄清性注释(如外部库说明)、TODO注释。
  • 糟糕的注释:含糊其辞、冗余、误导性、强制要求的、无意义的、位置标记类注释。

4. Formatting

4. 格式

  • The Newspaper Metaphor: High-level concepts at the top, details at the bottom.
  • Vertical Density: Related lines should be close to each other.
  • Distance: Variables should be declared near their usage.
  • Indentation: Essential for structural readability.
  • 报纸隐喻:高层概念放在顶部,细节放在底部。
  • 垂直密度:相关代码行应彼此靠近。
  • 距离:变量应在靠近使用的位置声明。
  • 缩进:对结构可读性至关重要。

5. Objects and Data Structures

5. 对象与数据结构

  • Data Abstraction: Hide the implementation behind interfaces.
  • The Law of Demeter: A module should not know about the innards of the objects it manipulates. Avoid
    a.getB().getC().doSomething()
    .
  • Data Transfer Objects (DTO): Classes with public variables and no functions.
  • 数据抽象:用接口隐藏实现细节。
  • 迪米特法则:模块不应了解它所操作对象的内部细节。避免
    a.getB().getC().doSomething()
    这种链式调用。
  • 数据传输对象(DTO):包含公共变量但无函数的类。

6. Error Handling

6. 错误处理

  • Use Exceptions instead of Return Codes: Keeps logic clean.
  • Write Try-Catch-Finally First: Defines the scope of the operation.
  • Don't Return Null: It forces the caller to check for null every time.
  • Don't Pass Null: Leads to
    NullPointerException
    .
  • 使用异常而非返回码:保持逻辑清晰。
  • 先编写Try-Catch-Finally:定义操作的范围。
  • 不要返回Null:这会迫使调用者每次都检查是否为Null。
  • 不要传递Null:会导致
    NullPointerException

7. Unit Tests

7. 单元测试

  • The Three Laws of TDD:
    1. Don't write production code until you have a failing unit test.
    2. Don't write more of a unit test than is sufficient to fail.
    3. Don't write more production code than is sufficient to pass the failing test.
  • F.I.R.S.T. Principles: Fast, Independent, Repeatable, Self-Validating, Timely.
  • TDD三定律:
    1. 除非有一个失败的单元测试,否则不要编写生产代码。
    2. 不要编写超出导致失败所需的单元测试代码。
    3. 不要编写超出通过失败测试所需的生产代码。
  • F.I.R.S.T.原则:快速(Fast)、独立(Independent)、可重复(Repeatable)、自验证(Self-Validating)、及时(Timely)。

8. Classes

8. 类

  • Small!: Classes should have a single responsibility (SRP).
  • The Stepdown Rule: We want the code to read like a top-down narrative.
  • 短小!:类应遵循单一职责原则(SRP)。
  • 逐步向下规则:代码应像自上而下的叙事一样易读。

9. Smells and Heuristics

9. 代码异味与启发法

  • Rigidity: Hard to change.
  • Fragility: Breaks in many places.
  • Immobility: Hard to reuse.
  • Viscosity: Hard to do the right thing.
  • Needless Complexity/Repetition.
  • 僵化性:难以修改。
  • 脆弱性:修改时多处崩溃。
  • 不可复用性:难以复用。
  • 粘性:难以做正确的事。
  • 不必要的复杂度/重复

🛠️ Implementation Checklist

🛠️ 实施检查清单

  • Is this function smaller than 20 lines?
  • Does this function do exactly one thing?
  • Are all names searchable and intention-revealing?
  • Have I avoided comments by making the code clearer?
  • Am I passing too many arguments?
  • Is there a failing test for this change?
  • 该函数是否少于20行?
  • 该函数是否只做一件事?
  • 所有名称是否都易搜索且能揭示意图?
  • 我是否通过优化代码来避免了注释?
  • 我是否传递了过多参数?
  • 此次修改是否有对应的失败测试?