clean-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Clean Code - Pragmatic AI Coding Standards

整洁代码 - 实用AI编码规范

CRITICAL SKILL - Be concise, direct, and solution-focused.

关键技能 - 要简洁、直接,以解决方案为核心

Core Principles

核心原则

PrincipleRule
SRPSingle Responsibility - each function/class does ONE thing
DRYDon't Repeat Yourself - extract duplicates, reuse
KISSKeep It Simple - simplest solution that works
YAGNIYou Aren't Gonna Need It - don't build unused features
Boy ScoutLeave code cleaner than you found it

原则规则
SRP单一职责 - 每个函数/类只做一件事
DRY避免重复 - 提取重复代码,复用逻辑
KISS保持简单 - 采用可行的最简方案
YAGNI你不会需要它 - 不要构建未使用的功能
童子军规则让代码比你接手时更整洁

Naming Rules

命名规则

ElementConvention
VariablesReveal intent:
userCount
not
n
FunctionsVerb + noun:
getUserById()
not
user()
BooleansQuestion form:
isActive
,
hasPermission
,
canEdit
ConstantsSCREAMING_SNAKE:
MAX_RETRY_COUNT
Rule: If you need a comment to explain a name, rename it.

元素约定
变量体现意图:
userCount
而非
n
函数动词+名词:
getUserById()
而非
user()
布尔值疑问形式:
isActive
,
hasPermission
,
canEdit
常量全大写下划线分隔:
MAX_RETRY_COUNT
规则: 如果你需要注释来解释命名,那就重命名它。

Function Rules

函数规则

RuleDescription
SmallMax 20 lines, ideally 5-10
One ThingDoes one thing, does it well
One LevelOne level of abstraction per function
Few ArgsMax 3 arguments, prefer 0-2
No Side EffectsDon't mutate inputs unexpectedly

规则描述
短小最多20行,理想是5-10行
单一职责只做一件事,并且做好
单一抽象层级每个函数只有一层抽象
少参数最多3个参数,优先0-2个
无副作用不要意外修改输入参数

Code Structure

代码结构

PatternApply
Guard ClausesEarly returns for edge cases
Flat > NestedAvoid deep nesting (max 2 levels)
CompositionSmall functions composed together
ColocationKeep related code close

模式应用场景
卫语句针对边缘情况提前返回
扁平优于嵌套避免深层嵌套(最多2层)
组合模式由小函数组合实现功能
就近原则相关代码放在一起

AI Coding Style

AI编码风格

SituationAction
User asks for featureWrite it directly
User reports bugFix it, don't explain
No clear requirementAsk, don't assume

场景操作
用户请求功能直接编写实现
用户报告Bug直接修复,无需解释
需求不明确询问用户,不要假设

Anti-Patterns (DON'T)

反模式(禁止)

❌ Pattern✅ Fix
Comment every lineDelete obvious comments
Helper for one-linerInline the code
Factory for 2 objectsDirect instantiation
utils.ts with 1 functionPut code where used
"First we import..."Just write code
Deep nestingGuard clauses
Magic numbersNamed constants
God functionsSplit by responsibility

❌ 模式✅ 修复方案
逐行添加注释删除冗余注释
为单行代码创建工具函数直接内联代码
为2个对象创建工厂类直接实例化对象
utils.ts中只有1个函数将代码移至使用处
"首先我们导入..."直接编写代码
深层嵌套使用卫语句
魔法数字使用命名常量
上帝函数按职责拆分

🔴 Before Editing ANY File (THINK FIRST!)

🔴 在编辑任何文件之前(先思考!)

Before changing a file, ask yourself:
QuestionWhy
What imports this file?They might break
What does this file import?Interface changes
What tests cover this?Tests might fail
Is this a shared component?Multiple places affected
Quick Check:
File to edit: UserService.ts
└── Who imports this? → UserController.ts, AuthController.ts
└── Do they need changes too? → Check function signatures
🔴 Rule: Edit the file + all dependent files in the SAME task. 🔴 Never leave broken imports or missing updates.

修改文件前,先问自己:
问题原因
哪些文件导入了当前文件?它们可能会被破坏
当前文件导入了哪些文件?接口变更可能影响依赖
哪些测试覆盖了当前文件?测试可能会失败
这是共享组件吗?变更会影响多个地方
快速检查示例:
File to edit: UserService.ts
└── Who imports this? → UserController.ts, AuthController.ts
└── Do they need changes too? → Check function signatures
🔴 规则: 在同一任务中编辑当前文件及所有依赖文件。 🔴 永远不要留下损坏的导入或未完成的更新。

Summary

总结

DoDon't
Write code directlyWrite tutorials
Let code self-documentAdd obvious comments
Fix bugs immediatelyExplain the fix first
Inline small thingsCreate unnecessary files
Name things clearlyUse abbreviations
Keep functions smallWrite 100+ line functions
Remember: The user wants working code, not a programming lesson.

要做不要做
直接编写代码编写教程式内容
让代码自文档化添加冗余注释
立即修复Bug先解释修复方案
内联小型代码创建不必要的文件
清晰命名使用缩写
保持函数短小编写100行以上的函数
记住:用户需要的是可运行的代码,而不是编程课程。

🔴 Self-Check Before Completing (MANDATORY)

🔴 完成任务前的自我检查(必须执行)

Before saying "task complete", verify:
CheckQuestion
Goal met?Did I do exactly what user asked?
Files edited?Did I modify all necessary files?
Code works?Did I test/verify the change?
No errors?Lint and TypeScript pass?
Nothing forgotten?Any edge cases missed?
🔴 Rule: If ANY check fails, fix it before completing.

在说"任务完成"前,验证以下内容:
检查项问题
达成目标?是否完全按照用户要求完成?
编辑了必要文件?是否修改了所有需要变更的文件?
代码可运行?是否测试/验证了变更?
无错误?Lint和TypeScript检查是否通过?
无遗漏?是否忽略了任何边缘情况?
🔴 规则: 只要有任何一项检查不通过,修复后再完成任务。

Verification Scripts (MANDATORY)

验证脚本(必须执行)

🔴 CRITICAL: Each agent runs ONLY their own skill's scripts after completing work.
🔴 关键: 每个Agent只能在完成工作后运行自己技能对应的脚本。

Agent → Script Mapping

Agent → 脚本映射

AgentScriptCommand
frontend-specialistUX Audit
python ~/.claude/skills/frontend-design/scripts/ux_audit.py .
frontend-specialistA11y Check
python ~/.claude/skills/frontend-design/scripts/accessibility_checker.py .
backend-specialistAPI Validator
python ~/.claude/skills/api-patterns/scripts/api_validator.py .
mobile-developerMobile Audit
python ~/.claude/skills/mobile-design/scripts/mobile_audit.py .
database-architectSchema Validate
python ~/.claude/skills/database-design/scripts/schema_validator.py .
security-auditorSecurity Scan
python ~/.claude/skills/vulnerability-scanner/scripts/security_scan.py .
seo-specialistSEO Check
python ~/.claude/skills/seo-fundamentals/scripts/seo_checker.py .
seo-specialistGEO Check
python ~/.claude/skills/geo-fundamentals/scripts/geo_checker.py .
performance-optimizerLighthouse
python ~/.claude/skills/performance-profiling/scripts/lighthouse_audit.py <url>
test-engineerTest Runner
python ~/.claude/skills/testing-patterns/scripts/test_runner.py .
test-engineerPlaywright
python ~/.claude/skills/webapp-testing/scripts/playwright_runner.py <url>
Any agentLint Check
python ~/.claude/skills/lint-and-validate/scripts/lint_runner.py .
Any agentType Coverage
python ~/.claude/skills/lint-and-validate/scripts/type_coverage.py .
Any agenti18n Check
python ~/.claude/skills/i18n-localization/scripts/i18n_checker.py .
WRONG:
test-engineer
running
ux_audit.py
CORRECT:
frontend-specialist
running
ux_audit.py

Agent脚本命令
frontend-specialistUX审计
python ~/.claude/skills/frontend-design/scripts/ux_audit.py .
frontend-specialist可访问性检查
python ~/.claude/skills/frontend-design/scripts/accessibility_checker.py .
backend-specialistAPI验证器
python ~/.claude/skills/api-patterns/scripts/api_validator.py .
mobile-developer移动审计
python ~/.claude/skills/mobile-design/scripts/mobile_audit.py .
database-architect模式验证
python ~/.claude/skills/database-design/scripts/schema_validator.py .
security-auditor安全扫描
python ~/.claude/skills/vulnerability-scanner/scripts/security_scan.py .
seo-specialistSEO检查
python ~/.claude/skills/seo-fundamentals/scripts/seo_checker.py .
seo-specialistGEO检查
python ~/.claude/skills/geo-fundamentals/scripts/geo_checker.py .
performance-optimizerLighthouse审计
python ~/.claude/skills/performance-profiling/scripts/lighthouse_audit.py <url>
test-engineer测试运行器
python ~/.claude/skills/testing-patterns/scripts/test_runner.py .
test-engineerPlaywright测试
python ~/.claude/skills/webapp-testing/scripts/playwright_runner.py <url>
Any agentLint检查
python ~/.claude/skills/lint-and-validate/scripts/lint_runner.py .
Any agent类型覆盖率
python ~/.claude/skills/lint-and-validate/scripts/type_coverage.py .
Any agent国际化检查
python ~/.claude/skills/i18n-localization/scripts/i18n_checker.py .
错误示例:
test-engineer
运行
ux_audit.py
正确示例:
frontend-specialist
运行
ux_audit.py

🔴 Script Output Handling (READ → SUMMARIZE → ASK)

🔴 脚本输出处理流程(阅读→总结→询问)

When running a validation script, you MUST:
  1. Run the script and capture ALL output
  2. Parse the output - identify errors, warnings, and passes
  3. Summarize to user in this format:
markdown
undefined
运行验证脚本时,你必须:
  1. 运行脚本 并捕获所有输出
  2. 解析输出 - 识别错误、警告和通过项
  3. 向用户总结 采用以下格式:
markdown
undefined

Script Results: [script_name.py]

脚本结果: [script_name.py]

❌ Errors Found (X items)

❌ 发现错误(X项)

  • [File:Line] Error description 1
  • [File:Line] Error description 2
  • [文件:行号] 错误描述1
  • [文件:行号] 错误描述2

⚠️ Warnings (Y items)

⚠️ 警告(Y项)

  • [File:Line] Warning description
  • [文件:行号] 警告描述

✅ Passed (Z items)

✅ 通过项(Z项)

  • Check 1 passed
  • Check 2 passed
Should I fix the X errors?

4. **Wait for user confirmation** before fixing
5. **After fixing** → Re-run script to confirm

> 🔴 **VIOLATION:** Running script and ignoring output = FAILED task.
> 🔴 **VIOLATION:** Auto-fixing without asking = Not allowed.
> 🔴 **Rule:** Always READ output → SUMMARIZE → ASK → then fix.
  • 检查项1通过
  • 检查项2通过
是否需要我修复这X个错误?

4. **等待用户确认** 后再进行修复
5. **修复完成后** → 重新运行脚本确认问题解决

> 🔴 **违规:** 运行脚本后忽略输出 = 任务失败。
> 🔴 **违规:** 未询问用户直接修复 = 不允许。
> 🔴 **规则:** 必须遵循 阅读输出→总结→询问→修复 的流程。