general-coding-guidelines

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

General Coding Guidelines

通用编码指南

1) Coding Principles

1) 编码原则

A) Correctness > Clarity > Consistency > Performance > Cleverness

A) 正确性 > 清晰性 > 一致性 > 性能 > 技巧性

  • Do not introduce clever abstractions.
  • Prefer boring, standard solutions that match the repo style.
  • 不要引入复杂的抽象实现。
  • 优先选择符合代码库风格的、常规的标准解决方案。

B) DRY (practical)

B) 实用版DRY(Don't Repeat Yourself,不要重复自己)

  • Avoid repeating logic that might change.
  • Avoid multiple large chunks of code in a single function.
  • Extract shared logic into:
    1. private method (same class)
    2. dedicated service (bounded context)
    3. helper (only if truly global and reusable)
  • 避免重复可能会变更的逻辑。
  • 避免在单个函数中写入大量代码块。
  • 将共享逻辑提取到:
    1. 私有方法(同一类中)
    2. 专用服务(限界上下文内)
    3. 工具函数(仅当确实是全局可复用的情况)

C) SOLID (practical)

C) 实用版SOLID原则

  • Classes/functions should have one reason to change.
  • Prefer composition over inheritance.
  • Depend on interfaces/contracts where it improves testability and flexibility.
  • 类/函数应该只有一个变更的理由。
  • 优先使用组合而非继承。
  • 在提升可测试性和灵活性的场景下,依赖接口/契约。

2) Variables & Functions (readability rules)

2) 变量与函数(可读性规则)

  • Prefer clear naming over fewer variables.
  • Inline values only if it improves clarity and avoids noise.
  • Extract a function when:
    • a block repeats,
    • a block is hard to name inline,
    • it improves testability.
  • 优先选择清晰的命名,而非更少的变量。
  • 只有当内联值能提升清晰度并减少冗余时,才使用内联值。
  • 在以下情况时提取函数:
    • 某代码块重复出现,
    • 某代码块难以用内联方式命名,
    • 提取后能提升可测试性。

3) Comments Policy

3) 注释规范

  • Avoid inline comments.
  • Prefer descriptive names and small functions.
  • Allowed comments:
    • Non-obvious constraints
    • Workarounds for external bugs
    • “Why” something is done (not “what”)
  • 避免行内注释。
  • 优先使用描述性命名和小函数。
  • 允许的注释类型:
    • 非显而易见的约束条件
    • 针对外部Bug的临时解决方案
    • 说明“为什么”要这么做(而非“做了什么”)

4) Database & Migrations Safety (language/framework-agnostic)

4) 数据库与迁移安全(与语言/框架无关)

  • Prefer additive, backwards-compatible schema changes when possible.
  • Avoid destructive changes unless explicitly required.
  • For destructive changes:
    • Call out irreversibility and data risk.
    • Provide a safe plan (two-step deploy or backfill approach).
  • For large tables:
    • Avoid long-running locks where possible.
    • Prefer online/low-lock patterns (nullable column → backfill in batches → add constraints).
  • Always consider rollback behavior:
    • Implement a rollback when feasible.
    • If rollback is unsafe, explicitly document it.
  • Never drop/rename in a way that breaks running code during rolling deploys unless coordinated.
  • 尽可能优先选择增量的、向后兼容的 schema 变更。
  • 除非明确要求,否则避免破坏性变更。
  • 对于破坏性变更:
    • 明确标注不可逆性和数据风险。
    • 提供安全的执行方案(分两步部署或回填数据的方式)。
  • 对于大型数据表:
    • 尽可能避免长时间的锁表操作。
    • 优先使用在线/低锁模式(可空列 → 分批回填数据 → 添加约束)。
  • 始终考虑回滚行为:
    • 若可行则实现回滚机制。
    • 若回滚存在风险,需明确记录。
  • 除非经过协调,否则绝不能以在滚动部署期间破坏运行中代码的方式删除/重命名对象。

5) Performance & Query Hygiene (framework-agnostic)

5) 性能与查询规范(与框架无关)

  • Default to clarity, but avoid obvious performance pitfalls.
  • When touching query/data-heavy code:
    • Avoid N+1-style behavior (load in batches, use joins/eager loading equivalents).
    • Avoid fetching full records when only checking existence/count.
    • Paginate/limit large result sets.
    • Select only needed fields for large reads.
  • Add indexes for frequently filtered/sorted columns where appropriate.
  • Mention any performance-related changes in Notes/Risks.
  • 默认优先保证代码清晰,但要避免明显的性能陷阱。
  • 处理查询/数据密集型代码时:
    • 避免N+1查询行为(批量加载,使用关联查询/预加载等效方案)。
    • 仅需检查存在性/计数时,避免获取完整记录。
    • 对大型结果集进行分页/限制数量。
    • 读取大量数据时仅选择所需字段。
  • 为频繁过滤/排序的列添加索引(如适用)。
  • 在“注意事项/风险”部分提及所有与性能相关的变更。

6) Git / Commits

6) Git / 提交规范

  • Do not commit changes unless otherwise instructed.
  • The user handles commits.
  • 除非另有指示,否则不要提交变更。
  • 由用户负责提交操作。

7) Linters / Static Analysis

7) 代码检查工具 / 静态分析

  • Do not run linters (eslint/phpstan/etc.) unless explicitly requested.
  • However, write code that would pass typical linters.
  • 除非明确要求,否则不要运行代码检查工具(如eslint、phpstan等)。
  • 但编写的代码应能通过常规的代码检查工具校验。

8) Global Helpers

8) 全局工具函数

  • Only create global helpers when reuse is likely across the codebase.
  • If you add global helpers, document them in the project's README or AGENTS.md.
  • 只有当工具函数大概率会在整个代码库中复用时,才创建全局工具函数。
  • 若添加全局工具函数,需在项目的README或AGENTS.md中进行文档记录。

9) Avoid code smells

9) 避免代码异味

Watch for and avoid these anti-patterns:
注意并避免以下反模式:

a) Long Functions

a) 过长函数

typescript
// ❌ BAD: Function > 50 lines
function processMarketData() {
  // 100 lines of code
}

// ✅ GOOD: Split into smaller functions
function processMarketData() {
  const validated = validateData()
  const transformed = transformData(validated)
  return saveData(transformed)
}
typescript
// ❌ BAD: Function > 50 lines
function processMarketData() {
  // 100 lines of code
}

// ✅ GOOD: Split into smaller functions
function processMarketData() {
  const validated = validateData()
  const transformed = transformData(validated)
  return saveData(transformed)
}

b) Deep Nesting

b) 深层嵌套

typescript
// ❌ BAD: 3+ levels of nesting
if (user) {
  if (user.isAdmin) {
    if (market) {
      if (market.isActive) {
        if (hasPermission) {
          // Do something
        }
      }
    }
  }
}

// ✅ GOOD: Early returns
if (!user) return
if (!user.isAdmin) return
if (!market) return
if (!market.isActive) return
if (!hasPermission) return

// Do something
typescript
// ❌ BAD: 3+ levels of nesting
if (user) {
  if (user.isAdmin) {
    if (market) {
      if (market.isActive) {
        if (hasPermission) {
          // Do something
        }
      }
    }
  }
}

// ✅ GOOD: Early returns
if (!user) return
if (!user.isAdmin) return
if (!market) return
if (!market.isActive) return
if (!hasPermission) return

// Do something

c) Magic Numbers

c) 魔法数字

php
// ❌ BAD: Unexplained numbers
if ($retryCount > 3) { }
set_time_limit(500);

// ✅ GOOD: Named constants
$MAX_RETRIES = 3;
$DEBOUNCE_DELAY_MS = 500;

if ($retryCount > $MAX_RETRIES) { }
set_time_limit($DEBOUNCE_DELAY_MS);
php
// ❌ BAD: Unexplained numbers
if ($retryCount > 3) { }
set_time_limit(500);

// ✅ GOOD: Named constants
$MAX_RETRIES = 3;
$DEBOUNCE_DELAY_MS = 500;

if ($retryCount > $MAX_RETRIES) { }
set_time_limit($DEBOUNCE_DELAY_MS);