clean-code
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClean Code for TypeScript/JavaScript
面向TypeScript/JavaScript的Clean Code实践
Practical patterns for writing and refactoring clean, maintainable TypeScript/JavaScript code.
提供编写、重构整洁可维护TypeScript/JavaScript代码的实用模式。
Code Smell Detection
代码异味检测
Naming Smells
命名异味
| Smell | Example | Fix |
|---|---|---|
| Single-letter names | | |
| Abbreviations | | |
| Generic names | | Name by what it represents |
| Misleading names | | |
| Encoding types | | |
| 异味 | 示例 | 修复方案 |
|---|---|---|
| 单字母命名 | | |
| 缩写命名 | | |
| 泛化命名 | | 按照实际代表的含义命名 |
| 误导性命名 | | |
| 类型嵌入命名 | | |
Function Smells
函数异味
| Smell | Indicator | Refactoring |
|---|---|---|
| Too many parameters | >3 params | Extract to options object |
| Flag arguments | | Split into separate functions |
| Side effects hidden | Function does more than name suggests | Rename or split |
| God function | >20 lines or multiple responsibilities | Extract smaller functions |
| Deep nesting | >3 levels of indentation | Early returns, extract functions |
| 异味 | 特征 | 重构方案 |
|---|---|---|
| 参数过多 | 参数数量>3 | 抽离为配置对象 |
| 标记参数 | | 拆分为独立函数 |
| 隐藏副作用 | 函数实际功能与名称描述不符 | 重命名或者拆分函数 |
| 上帝函数 | 代码行数>20或承担多个职责 | 抽离为多个更小的函数 |
| 深层嵌套 | 缩进层级>3 | 提前返回、抽离函数 |
Structure Smells
结构异味
| Smell | Indicator | Refactoring |
|---|---|---|
| Long file | >300 lines | Split by responsibility |
| Feature envy | Function uses another object's data extensively | Move to that object |
| Data clumps | Same group of params passed together | Extract to type/class |
| Primitive obsession | Using primitives for domain concepts | Create value objects |
| Switch on type | | Polymorphism or lookup |
| 异味 | 特征 | 重构方案 |
|---|---|---|
| 文件过长 | 代码行数>300 | 按职责拆分文件 |
| 特性依恋 | 函数大量使用其他对象的数据 | 将函数移动到对应对象中 |
| 数据泥团 | 同一组参数被反复传递 | 抽离为类型/类 |
| 基础类型偏执 | 对领域概念使用基础类型表示 | 创建值对象 |
| 类型判断分支 | | 多态或者查找表 |
Refactoring Patterns
重构模式
For detailed before/after code examples, see references/refactoring-patterns.md.
Quick reference:
- Guard clauses — Replace nested if/else with early returns
- Object lookup — Replace switch/if-else chains with Record mapping
- Options object — Replace >3 parameters with a single options object
- Named constants — Replace magic numbers/strings with descriptive constants
- Extract function — Break god functions into single-responsibility pieces
- Flatten ternaries — Replace nested ternaries with lookup or function
- Consolidate duplicates — Extract repeated logic into shared functions
- Simplify booleans — Return condition directly instead of if/else true/false
- Array methods — Replace manual loops with filter/map/reduce
- Destructure — Use destructuring for cleaner property access
如需查看详细的代码前后对比示例,请查看references/refactoring-patterns.md。
快速参考:
- 守卫子句 — 用提前返回替代嵌套if/else
- 对象查找 — 用Record映射替代switch/if-else分支链
- 配置对象 — 用单个配置对象替代超过3个的入参
- 命名常量 — 用含义明确的常量替代魔术数字/字符串
- 函数抽取 — 将上帝函数拆分为多个单一职责的小函数
- 扁平化三元运算 — 用查找表或者函数替代嵌套三元运算
- 重复逻辑合并 — 将重复出现的逻辑抽离为共享函数
- 布尔值简化 — 直接返回条件判断结果,替代if/else返回true/false的写法
- 数组方法 — 用filter/map/reduce替代手动循环
- 解构 — 使用解构实现更简洁的属性访问
Naming Conventions
命名规范
Functions
函数
- Actions: verb + noun → ,
createUser,validateInputfetchOrders - Booleans: is/has/can/should prefix → ,
isValid,hasPermissioncanEdit - Event handlers: handle + event → ,
handleClickhandleSubmit - Transformers: to/from/parse/format → ,
toJSON,fromDTOparseDate
- 动作类:动词+名词 → 、
createUser、validateInputfetchOrders - 布尔返回类:使用is/has/can/should前缀 → 、
isValid、hasPermissioncanEdit - 事件处理类:handle+事件名 → 、
handleClickhandleSubmit - 转换类:to/from/parse/format前缀 → 、
toJSON、fromDTOparseDate
Variables
变量
- Booleans: positive names → not
isEnabledisNotDisabled - Arrays/collections: plural → ,
usersorderItems - Counts: noun + Count → ,
retryCounterrorCount
- 布尔类型:使用肯定含义命名 → 用而非
isEnabledisNotDisabled - 数组/集合类型:使用复数形式 → 、
usersorderItems - 计数类:名词+Count → 、
retryCounterrorCount
Constants
常量
- Module-level: SCREAMING_SNAKE_CASE → ,
MAX_RETRIESAPI_BASE_URL - Enum-like objects: PascalCase key, values match usage →
Status.Active
- 模块级别常量:全大写下划线分隔 → 、
MAX_RETRIESAPI_BASE_URL - 类枚举对象:键使用大驼峰,值匹配使用场景 →
Status.Active
Quick Refactoring Checklist
快速重构检查清单
When reviewing code for cleanliness:
- Names — Can you understand intent without reading implementation?
- Functions — Does each do exactly one thing? <20 lines?
- Parameters — More than 3? Extract to object
- Nesting — More than 2 levels? Use early returns
- Duplication — Same logic in 2+ places? Extract
- Magic values — Any unexplained numbers/strings? Name them
- Comments — Explaining "what"? Rewrite code to be self-explanatory
- Dead code — Commented-out code or unused vars? Delete
评审代码整洁度时可参考以下项:
- 命名 — 不看具体实现能否理解代码意图?
- 函数 — 每个函数是否只做一件事?代码行数是否<20?
- 参数 — 入参是否超过3个?可抽离为配置对象?
- 嵌套 — 嵌套层级是否超过2层?可使用提前返回优化?
- 重复 — 同一逻辑是否出现在2个以上位置?可抽离复用?
- 魔术值 — 是否存在无说明的数字/字符串?可命名为常量?
- 注释 — 注释是否在解释“做了什么”?可优化代码使其自解释?
- 死代码 — 是否存在注释掉的代码或者未使用的变量?可删除?
Anti-Patterns to Avoid
需要避免的反模式
Over-Engineering
过度工程
- Don't create abstractions for single-use cases
- Don't add configurability "for the future"
- Don't wrap simple operations in utility functions
- 不要为仅使用一次的场景创建抽象
- 不要“为了未来可能的需求”额外添加可配置性
- 不要把简单操作封装到多余的工具函数里
Under-Engineering
工程不足
- Don't ignore repeated patterns (3+ occurrences = extract)
- Don't leave deeply nested code unrefactored
- Don't use to avoid typing properly
any
- 不要忽略重复出现的模式(出现3次及以上就可以抽离复用)
- 不要留下深层嵌套的代码不重构
- 不要用来逃避正确的类型定义
any
Wrong Abstraction
错误抽象
- Don't force inheritance when composition works
- Don't create god classes that do everything
- Don't split tightly coupled logic across files
- 组合更合适时不要强行使用继承
- 不要创建承担所有职责的上帝类
- 不要把强耦合的逻辑拆分到多个文件中