Loading...
Loading...
Compare original and translation side by side
Non-negotiable code quality standards. These are not preferences — they are requirements.
不可妥协的代码质量标准。这些并非偏好选择——而是硬性要求。
| Layer | What it Tests | Speed | Purpose |
|---|---|---|---|
| Unit Tests | Individual functions/components | Fast | TDD lives here. Catches logic errors early. |
| Integration Tests | Components working together | Medium | Catches connection and data flow issues. |
| E2E Tests | Full user flows | Slowest | Confirms the system does the thing. |
| Human Review | Visual correctness, UX | Manual | Irreducible quality judgment. |
| 层级 | 测试对象 | 执行速度 | 核心目的 |
|---|---|---|---|
| 单元测试 | 独立函数/组件 | 极快 | TDD的核心应用场景,尽早捕获逻辑错误。 |
| 集成测试 | 协同工作的组件 | 中等 | 捕获组件间的连接与数据流问题。 |
| 端到端(E2E)测试 | 完整用户流程 | 最慢 | 确认系统可完成预期业务功能。 |
| 人工评审 | 视觉正确性、用户体验(UX) | 手动 | 无法替代的主观质量判断环节。 |
def test_apply_discount_reduces_total():
# Arrange — set up the scenario
cart = Cart(items=[Item(price=100)])
discount = Discount(percent=20)
# Act — perform the action under test
cart.apply_discount(discount)
# Assert — verify the outcome
assert cart.total == 80| Bad | Good |
|---|---|
| |
| |
| |
def test_apply_discount_reduces_total():
# Arrange — set up the scenario
cart = Cart(items=[Item(price=100)])
discount = Discount(percent=20)
# Act — perform the action under test
cart.apply_discount(discount)
# Assert — verify the outcome
assert cart.total == 80| 不良示例 | 优质示例 |
|---|---|
| |
| |
| |
def process(order):
if order:
if order.items:
if order.is_valid:
return calculate_total(order)
return Nonedef process(order):
if not order:
return None
if not order.items:
return None
if not order.is_valid:
return None
return calculate_total(order)def process(order):
if order:
if order.items:
if order.is_valid:
return calculate_total(order)
return Nonedef process(order):
if not order:
return None
if not order.items:
return None
if not order.is_valid:
return None
return calculate_total(order)validateformatsavevalidateformatsavenames = [u.name for u in users if u.is_active and u.role in allowed]active_users = filter_active(users)
authorized_users = filter_by_role(active_users, allowed)
names = extract_names(authorized_users)names = [u.name for u in users if u.is_active and u.role in allowed]active_users = filter_active(users)
authorized_users = filter_by_role(active_users, allowed)
names = extract_names(authorized_users)def create_user(email, name):
if not email:
raise ValidationError("Email is required")
if not is_valid_email(email):
raise ValidationError("Invalid email format")
return save_user(email, name)def create_user(email, name):
if not email:
raise ValidationError("Email is required")
if not is_valid_email(email):
raise ValidationError("Invalid email format")
return save_user(email, name)try:
do_risky_thing()
except Exception:
passtry:
do_risky_thing()
except NetworkError:
return retry()
except ValidationError as e:
return error_response(e.message)try:
do_risky_thing()
except Exception:
passtry:
do_risky_thing()
except NetworkError:
return retry()
except ValidationError as e:
return error_response(e.message)undefinedundefinedcatchexceptcatchexcepttofromintoontoshop.buy_item(item_id, buyer) # Who is buying?
transfer(amount, account) # Transfer to or from?shop.sell_item_to(item_id, buyer) # Shop sells TO buyer
shop.sell(item_id, to=buyer) # Named parameter clarifies
transfer_from(account, amount) # Direction explicit
account.transfer_to(other, amount) # Direction in method nametofromintoontoshop.buy_item(item_id, buyer) # 谁在购买?
transfer(amount, account) # 转入还是转出?shop.sell_item_to(item_id, buyer) # 商店售卖给买家
shop.sell(item_id, to=buyer) # 命名参数明确流向
transfer_from(account, amount) # 流向明确
account.transfer_to(other, amount) # 方法名包含流向undefinedundefinedundefinedundefinedishasshouldcanwilldidundefinedishasshouldcanwilldidundefinedundefinedundefined| Pattern | Use When | Example |
|---|---|---|
| Action flows to target | |
| Action flows from source | |
| Object performs action toward target | |
| Named parameter clarifies | |
| 模式 | 使用场景 | 示例 |
|---|---|---|
| 动作流向目标 | |
| 动作来自源 | |
| 对象执行朝向目标的动作 | |
| 命名参数明确流向 | |
| Don't | Instead |
|---|---|
Single letters (except loop | Full descriptive name |
Abbreviations ( | |
Generic names ( | |
Negated booleans ( | |
| 不要做 | 替代方案 |
|---|---|
使用单个字母(循环变量 | 使用完整描述性名称 |
使用缩写( | |
使用通用名称( | |
使用否定式布尔值( | |
if retry_count > 3:
sleep(60)MAX_RETRIES = 3
RETRY_DELAY_SECONDS = 60
if retry_count > MAX_RETRIES:
sleep(RETRY_DELAY_SECONDS)if retry_count > 3:
sleep(60)MAX_RETRIES = 3
RETRY_DELAY_SECONDS = 60
if retry_count > MAX_RETRIES:
sleep(RETRY_DELAY_SECONDS)Truecreate_user(data, True, False)create_user(data, send_welcome=True, require_verification=False)Truecreate_user(data, True, False)create_user(data, send_welcome=True, require_verification=False)def sell_item_to(self, item_id: str, buyer: Customer) -> Receipt:
"""Sell an item from shop inventory to a customer.
Transfers ownership of the item from the shop to the buyer,
processes payment, and updates inventory.
Args:
item_id: Unique identifier of the item to sell.
buyer: Customer purchasing the item. Must have sufficient balance.
Returns:
Receipt containing transaction details and timestamp.
Raises:
ItemNotFoundError: If item_id doesn't exist in inventory.
InsufficientBalanceError: If buyer can't afford the item.
ItemAlreadySoldError: If item was sold between check and purchase.
Examples:
Basic sale:
>>> shop = Shop(inventory=[item])
>>> buyer = Customer(balance=100)
>>> receipt = shop.sell_item_to(item.id, buyer)
>>> assert receipt.amount == item.price
>>> assert item.id not in shop.inventory
Handling insufficient balance:
>>> poor_buyer = Customer(balance=0)
>>> shop.sell_item_to(item.id, poor_buyer)
Raises InsufficientBalanceError
"""def sell_item_to(self, item_id: str, buyer: Customer) -> Receipt:
"""Sell an item from shop inventory to a customer.
Transfers ownership of the item from the shop to the buyer,
processes payment, and updates inventory.
Args:
item_id: Unique identifier of the item to sell.
buyer: Customer purchasing the item. Must have sufficient balance.
Returns:
Receipt containing transaction details and timestamp.
Raises:
ItemNotFoundError: If item_id doesn't exist in inventory.
InsufficientBalanceError: If buyer can't afford the item.
ItemAlreadySoldError: If item was sold between check and purchase.
Examples:
Basic sale:
>>> shop = Shop(inventory=[item])
>>> buyer = Customer(balance=100)
>>> receipt = shop.sell_item_to(item.id, buyer)
>>> assert receipt.amount == item.price
>>> assert item.id not in shop.inventory
Handling insufficient balance:
>>> poor_buyer = Customer(balance=0)
>>> shop.sell_item_to(item.id, poor_buyer)
Raises InsufficientBalanceError
"""| Do Comment | Don't Comment |
|---|---|
| Why — intent, business reason, non-obvious context | What — the code already says this |
| Non-obvious gotchas or edge cases | Obvious operations |
| Complex algorithm summaries | Bad code to explain it (fix the code instead) |
| TODO with ticket/issue reference | TODO without context |
| 应注释内容 | 不应注释内容 |
|---|---|
| 原因 —— 意图、业务背景、非显而易见的上下文 | 内容 —— 代码本身已说明 |
| 非显而易见的陷阱或边缘情况 | 明显的操作 |
| 复杂算法的摘要 | 用注释解释坏代码(应直接修复代码) |
| 包含工单/问题引用的TODO | 无上下文的TODO |
references/testing-reference.mdreferences/naming-reference.mdreferences/error-handling-reference.mdreferences/testing-reference.mdreferences/naming-reference.mdreferences/error-handling-reference.mdassets/tdd-checklist.mdassets/docstring-templates.mdassets/code-review-checklist.mdassets/tdd-checklist.mdassets/docstring-templates.mdassets/code-review-checklist.mdscripts/check_naming.pyscripts/check_complexity.pyscripts/check_naming.pyscripts/check_complexity.py