本技能赋能 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.