code-style
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode Style
代码风格
Core Philosophy
核心理念
Code should be self-explanatory. Comments explain WHY, not WHAT.
代码应具备自解释性。注释用于解释原因,而非内容。
Function Design
函数设计
Small and Focused
小巧且聚焦单一职责
Each function should do one thing well. Split larger functions into smaller, independent methods.
每个函数应只做好一件事。将大型函数拆分为更小、独立的方法。
Either Call Or Pass
要么调用要么执行
A function should either:
- Call other methods (high-level orchestration), OR
- Pass data / perform low-level operations
Never mix abstraction levels in one function body. This is the Single Level of Abstraction (SLA) principle.
typescript
// BAD - mixed abstraction levels
function processOrder(order: Order) {
validateOrder(order); // high-level call
const tax = order.total * 0.1; // low-level calculation
await sendConfirmation(order); // high-level call
db.insert('orders', { ...order, tax }); // low-level operation
}
// GOOD - consistent abstraction
function processOrder(order: Order) {
validateOrder(order);
const enrichedOrder = calculateTaxes(order);
await persistOrder(enrichedOrder);
await sendConfirmation(enrichedOrder);
}一个函数应该:
- 调用其他方法(高层编排),或者
- 传递数据 / 执行底层操作
绝不要在一个函数体中混合不同抽象层级。这就是单一抽象层级(SLA)原则。
typescript
// BAD - mixed abstraction levels
function processOrder(order: Order) {
validateOrder(order); // high-level call
const tax = order.total * 0.1; // low-level calculation
await sendConfirmation(order); // high-level call
db.insert('orders', { ...order, tax }); // low-level operation
}
// GOOD - consistent abstraction
function processOrder(order: Order) {
validateOrder(order);
const enrichedOrder = calculateTaxes(order);
await persistOrder(enrichedOrder);
await sendConfirmation(enrichedOrder);
}Never Use If With Else
避免使用If-Else结构
Prefer guard clauses or polymorphism over if-else blocks.
typescript
// BAD
function getDiscount(user: User) {
if (user.isPremium) {
return 0.2;
} else {
return 0;
}
}
// GOOD - guard clause
function getDiscount(user: User) {
if (!user.isPremium) return 0;
return 0.2;
}优先使用卫语句或多态而非if-else块。
typescript
// BAD
function getDiscount(user: User) {
if (user.isPremium) {
return 0.2;
} else {
return 0;
}
}
// GOOD - guard clause
function getDiscount(user: User) {
if (!user.isPremium) return 0;
return 0.2;
}Avoid Flag Arguments
避免标志参数
Flag arguments indicate a function is doing more than one thing.
typescript
// BAD
function createUser(data: UserData, sendEmail: boolean) { ... }
// GOOD
function createUser(data: UserData) { ... }
function createUserAndNotify(data: UserData) { ... }标志参数表明一个函数正在做不止一件事。
typescript
// BAD
function createUser(data: UserData, sendEmail: boolean) { ... }
// GOOD
function createUser(data: UserData) { ... }
function createUserAndNotify(data: UserData) { ... }Naming
命名规范
Expressive Over Comments
用有意义的命名替代注释
typescript
// BAD
const d = 7; // days in recovery period
// GOOD
const daysInRecoveryPeriod = 7;typescript
// BAD
const d = 7; // days in recovery period
// GOOD
const daysInRecoveryPeriod = 7;No Abbreviations
禁止使用缩写
typescript
// BAD
getUserCmt(), calcRecReq()
// GOOD
getUserComment(), calculateRecoveryRequirement()typescript
// BAD
getUserCmt(), calcRecReq()
// GOOD
getUserComment(), calculateRecoveryRequirement()Booleans Read Like Questions
布尔值命名应像疑问句
typescript
// BAD
eligible, recovery
// GOOD
isEligible, isRecovering, hasPassedDeadlinetypescript
// BAD
eligible, recovery
// GOOD
isEligible, isRecovering, hasPassedDeadlineCollections Use Plurals
集合类型使用复数命名
typescript
// BAD
const post = getPosts();
// GOOD
const posts = getPosts();typescript
// BAD
const post = getPosts();
// GOOD
const posts = getPosts();Use Intermediate Variables
使用中间变量
typescript
const hasRequiredPostCount = posts.length >= 2;
const isWithinRecoveryWindow = new Date() <= recoveryDeadline;
const canStartRecovery = hasRequiredPostCount && isWithinRecoveryWindow;typescript
const hasRequiredPostCount = posts.length >= 2;
const isWithinRecoveryWindow = new Date() <= recoveryDeadline;
const canStartRecovery = hasRequiredPostCount && isWithinRecoveryWindow;Constants
常量
No Magic Numbers
禁止使用魔法数字
typescript
// BAD
if (streak >= 21) { ... }
// GOOD
const GOLD_BADGE_STREAK_THRESHOLD = 21;
if (streak >= GOLD_BADGE_STREAK_THRESHOLD) { ... }typescript
// BAD
if (streak >= 21) { ... }
// GOOD
const GOLD_BADGE_STREAK_THRESHOLD = 21;
if (streak >= GOLD_BADGE_STREAK_THRESHOLD) { ... }Comments
注释
Sparingly and Meaningful
少而精
- Code tells HOW, comments tell WHY
- If you need a comment, first try better naming
- Use for known limitations
TODO: - Delete obsolete comments
- 代码说明实现方式,注释说明原因
- 如果需要注释,先尝试优化命名
- 使用标记已知限制
TODO: - 删除过时注释