clean-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Clean Code Skill

《Clean Code(代码整洁之道)》技能

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."
本技能体现了罗伯特·C·马丁(鲍勃大叔,Uncle Bob)所著《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)

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
    # Check if employee is eligible for full benefits
    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:会导致
    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行?
  • 该函数是否严格只做一件事?
  • 所有命名是否都易于搜索、表意清晰?
  • 我是否已经通过优化代码清晰性避免了不必要的注释?
  • 我是否传递了过多的参数?
  • 本次修改是否有对应的失败测试用例?