ogt-docs-rules-code
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOGT Docs - Rules Code
OGT 文档 - 代码规则
Complete guide for creating and managing coding standards and rules.
创建和管理编码规范与规则的完整指南。
Overview
概述
Coding rules establish consistent patterns across the codebase. They are enforceable (via linters, type checkers, CI) and documented with examples.
mermaid
flowchart TB
subgraph code ["docs/rules/code/"]
G["general/"]
TS["typescript/"]
N["naming/"]
E["errors/"]
A["async/"]
subgraph front ["front/"]
FC["components/"]
FS["state/"]
FST["styling/"]
end
subgraph back ["back/"]
BA["api/"]
BD["database/"]
BS["services/"]
end
end
G --> TS
G --> N
G --> E
G --> A编码规则用于在整个代码库中建立一致的模式。它们可通过代码检查器(linter)、类型检查器、CI等工具强制执行,并附带示例文档。
mermaid
flowchart TB
subgraph code ["docs/rules/code/"]
G["general/"]
TS["typescript/"]
N["naming/"]
E["errors/"]
A["async/"]
subgraph front ["front/"]
FC["components/"]
FS["state/"]
FST["styling/"]
end
subgraph back ["back/"]
BA["api/"]
BD["database/"]
BS["services/"]
end
end
G --> TS
G --> N
G --> E
G --> AWhen to Use
适用场景
- Creating new coding standards
- Documenting TypeScript patterns
- Establishing naming conventions
- Defining error handling patterns
- Setting architecture rules
- Updating existing code rules
- 创建新的编码规范
- 记录TypeScript模式
- 制定命名约定
- 定义错误处理模式
- 设置架构规则
- 更新现有代码规则
Folder Structure
目录结构
docs/rules/code/
├── general/ # Cross-cutting rules
│ ├── rule.md
│ ├── examples.md
│ ├── .version
│ └── .enforced_by
│
├── typescript/ # TypeScript-specific
│ ├── strict_mode/
│ ├── type_assertions/
│ ├── generics/
│ └── unions/
│
├── naming/ # Naming conventions
│ ├── files/
│ ├── variables/
│ ├── functions/
│ ├── types/
│ └── constants/
│
├── errors/ # Error handling
│ ├── catching/
│ ├── throwing/
│ └── logging/
│
├── async/ # Async patterns
│ ├── promises/
│ └── error_handling/
│
├── imports/ # Import organization
│ ├── ordering/
│ └── barrel_files/
│
├── front/ # Frontend-specific
│ ├── components/
│ ├── state/
│ ├── hooks/
│ └── styling/
│
└── back/ # Backend-specific
├── api/
├── database/
└── services/docs/rules/code/
├── general/ # 通用规则(跨领域)
│ ├── rule.md
│ ├── examples.md
│ ├── .version
│ └── .enforced_by
│
├── typescript/ # TypeScript专属规则
│ ├── strict_mode/
│ ├── type_assertions/
│ ├── generics/
│ └── unions/
│
├── naming/ # 命名约定
│ ├── files/
│ ├── variables/
│ ├── functions/
│ ├── types/
│ └── constants/
│
├── errors/ # 错误处理规则
│ ├── catching/
│ ├── throwing/
│ └── logging/
│
├── async/ # 异步模式规则
│ ├── promises/
│ └── error_handling/
│
├── imports/ # 导入组织规则
│ ├── ordering/
│ └── barrel_files/
│
├── front/ # 前端专属规则
│ ├── components/
│ ├── state/
│ ├── hooks/
│ └── styling/
│
└── back/ # 后端专属规则
├── api/
├── database/
└── services/Example: docs/rules/code/general/
示例:docs/rules/code/general/
Root coding standards that apply everywhere.
适用于所有场景的核心编码规范。
Folder Structure
目录结构
docs/rules/code/general/
├── rule.md
├── examples.md
├── .version
└── .enforced_bydocs/rules/code/general/
├── rule.md
├── examples.md
├── .version
└── .enforced_byrule.md
rule.md
markdown
undefinedmarkdown
undefinedRule: General Coding Standards
规则:通用编码规范
Summary
概述
All code MUST follow these fundamental standards for consistency and maintainability.
所有代码必须遵循这些基础规范,以保证一致性和可维护性。
Rationale
设计初衷
Consistent code is easier to read, review, maintain, and debug.
一致的代码更易于阅读、评审、维护和调试。
The Rules
具体规则
1. Single Responsibility
1. 单一职责原则
Each function, class, or module MUST have one clear purpose.
- Functions SHOULD be under 30 lines
- Files SHOULD be under 300 lines
每个函数、类或模块必须有明确的单一职责。
- 函数代码行数应控制在30行以内
- 文件代码行数应控制在300行以内
2. Explicit Over Implicit
2. 显式优于隐式
- MUST NOT rely on implicit type coercion
- MUST use explicit return statements
- MUST use explicit comparisons (not
===)==
- 禁止依赖隐式类型转换
- 必须使用显式返回语句
- 必须使用显式比较(使用而非
===)==
3. Fail Fast
3. 快速失败原则
- MUST validate function parameters at entry
- MUST throw on invalid input (not return null)
- 必须在函数入口处验证参数
- 必须在输入无效时抛出错误(而非返回null)
4. No Magic Values
4. 禁用魔法值
- MUST extract magic numbers to named constants
- MUST extract magic strings to constants or enums
- 必须将魔法数字提取为命名常量
- 必须将魔法字符串提取为常量或枚举
5. Immutability Preference
5. 优先使用不可变数据
- SHOULD use over
constlet - MUST NOT use
var - SHOULD prefer spread over mutation
- 推荐使用而非
constlet - 禁止使用
var - 推荐使用扩展运算符(spread)而非直接修改原数据
Examples
示例
Correct
正确示例
typescript
// Named constants
const MAX_RETRY_ATTEMPTS = 3;
const CACHE_TTL_MS = 60 * 1000;
// Explicit comparisons
if (user.role === 'admin') { ... }
// Immutable update
const updatedUser = { ...user, lastLogin: new Date() };undefinedtypescript
// 命名常量
const MAX_RETRY_ATTEMPTS = 3;
const CACHE_TTL_MS = 60 * 1000;
// 显式比较
if (user.role === 'admin') { ... }
// 不可变更新
const updatedUser = { ...user, lastLogin: new Date() };undefinedIncorrect
错误示例
typescript
// Magic values
setTimeout(callback, 86400000); // What is this?
// Implicit coercion
if (user.role == 'admin') { ... } // Use ===
// Mutation
user.lastLogin = new Date(); // Mutates originaltypescript
// 魔法值
setTimeout(callback, 86400000); // 这个数值代表什么?
// 隐式类型转换
if (user.role == 'admin') { ... } // 应使用===
// 直接修改原数据
user.lastLogin = new Date(); // 修改了原始对象Enforcement
强制执行方式
- ESLint rules
- TypeScript strict mode
- Code review
undefined- ESLint规则
- TypeScript严格模式
- 代码评审
undefined.enforced_by
.enforced_by
eslint
typescript strict mode
code review
eslint
typescript strict mode
code review
Example: docs/rules/code/naming/files/
示例:docs/rules/code/naming/files/
File naming conventions.
文件命名约定规则。
rule.md
rule.md
markdown
undefinedmarkdown
undefinedRule: File Naming Conventions
规则:文件命名约定
Summary
概述
All source files MUST follow consistent naming patterns based on content type.
所有源文件必须根据内容类型遵循一致的命名模式。
The Rules
具体规则
| Type | Pattern | Example |
|---|---|---|
| React Component | | |
| React Hook | | |
| Service | | |
| Utility | | |
| Types | | |
| Test | | |
| Index/Barrel | | |
| 类型 | 命名模式 | 示例 |
|---|---|---|
| React组件 | | |
| React Hook | | |
| 服务类 | | |
| 工具类 | | |
| 类型定义 | | |
| 测试文件 | | |
| 索引文件/桶文件 | | |
Directory Names
目录命名规则
- MUST use kebab-case for directories
- SHOULD match domain concept (plural for collections)
- 必须使用kebab-case命名目录
- 推荐目录名与业务领域概念匹配(集合类使用复数形式)
Examples
示例
Correct
正确示例
src/
components/
creatures/
CreatureCard.tsx
creature-card.types.ts
index.ts
hooks/
use-creature-data.ts
services/
auth-service.ts
```
src/
components/
creatures/
CreatureCard.tsx
creature-card.types.ts
index.ts
hooks/
use-creature-data.ts
services/
auth-service.ts
```Incorrect
错误示例
src/
Components/ # Should be lowercase
CreatureCards/ # Should be kebab-case
creatureCard.tsx # Should be PascalCase
Hooks/
useCreatureData.ts # Should be use-creature-data.ts
src/
Components/ # 应使用小写
CreatureCards/ # 应使用kebab-case
creatureCard.tsx # 应使用PascalCase
Hooks/
useCreatureData.ts # 应使用use-creature-data.ts
Enforcement
强制执行方式
- ESLint file naming plugin
- Pre-commit hook
---- ESLint文件命名插件
- 提交前钩子(Pre-commit hook)
---Example: docs/rules/code/errors/catching/
示例:docs/rules/code/errors/catching/
Error handling rules.
错误捕获规则。
rule.md
rule.md
markdown
undefinedmarkdown
undefinedRule: Error Catching
规则:错误捕获
Summary
概述
All caught errors MUST be properly typed, logged, and handled - never silently swallowed.
所有捕获的错误必须正确标注类型、记录日志并进行处理——绝对不能静默忽略。
The Rules
具体规则
1. Never Catch and Ignore
1. 禁止捕获后忽略错误
MUST NOT have empty catch blocks.
禁止使用空的catch块。
2. Type Caught Errors
2. 为捕获的错误标注类型
MUST type errors as and narrow appropriately.
unknowntypescript
try {
await fetchData();
} catch (error: unknown) {
if (error instanceof NetworkError) {
handleNetworkError(error);
} else if (error instanceof Error) {
handleGenericError(error);
}
}undefined必须将错误标注为类型,并适当缩小类型范围。
unknowntypescript
try {
await fetchData();
} catch (error: unknown) {
if (error instanceof NetworkError) {
handleNetworkError(error);
} else if (error instanceof Error) {
handleGenericError(error);
}
}undefined3. Log Before Rethrowing
3. 重新抛出前记录日志
MUST log errors if rethrowing or transforming.
必须在重新抛出或转换错误前记录日志。
4. Recover or Fail Gracefully
4. 恢复或优雅降级
MUST either recover meaningfully or fail gracefully.
必须要么进行有意义的恢复,要么优雅地失败。
Examples
示例
Correct
正确示例
typescript
async function fetchUser(id: string): Promise<User> {
try {
return await api.get(`/users/${id}`);
} catch (error: unknown) {
if (isNotFoundError(error)) {
throw new UserNotFoundError(id);
}
logger.error("Unexpected error", { id, error });
throw error;
}
}typescript
async function fetchUser(id: string): Promise<User> {
try {
return await api.get(`/users/${id}`);
} catch (error: unknown) {
if (isNotFoundError(error)) {
throw new UserNotFoundError(id);
}
logger.error("Unexpected error", { id, error });
throw error;
}
}Incorrect
错误示例
typescript
// Silent swallow - FORBIDDEN
try {
await saveAnalytics(event);
} catch (e) {}
// Untyped error access
try {
await fetchData();
} catch (e) {
console.log(e.message); // e is unknown!
}typescript
// 静默忽略错误——禁止使用
try {
await saveAnalytics(event);
} catch (e) {}
// 未标注类型就访问错误属性
try {
await fetchData();
} catch (e) {
console.log(e.message); // e的类型是unknown!
}Enforcement
强制执行方式
- ESLint no-empty catch
- TypeScript useUnknownInCatchVariables
---- ESLint no-empty-catch规则
- TypeScript useUnknownInCatchVariables选项
---Example: docs/rules/code/async/promises/
示例:docs/rules/code/async/promises/
Async/await patterns.
异步/等待模式规则。
rule.md
rule.md
markdown
undefinedmarkdown
undefinedRule: Promise Handling
规则:Promise处理
Summary
概述
All Promises MUST be properly awaited or have rejections handled.
所有Promise必须正确等待(await)或处理拒绝(rejection)。
The Rules
具体规则
1. Always Await or Handle
1. 必须等待或处理Promise
typescript
// CORRECT - awaited
const data = await fetchData();
// CORRECT - fire-and-forget with handler
sendAnalytics(event).catch(logError);
// FORBIDDEN - floating promise
fetchData(); // No await, no handlertypescript
// 正确——已等待
const data = await fetchData();
// 正确——无需等待但已处理错误
sendAnalytics(event).catch(logError);
// 错误——游离的Promise(未等待也未处理)
fetchData(); // 没有await,也没有错误处理2. Use async/await Over .then()
2. 优先使用async/await而非.then()
SHOULD prefer async/await for readability.
推荐使用async/await以提升可读性。
3. Parallel When Independent
3. 独立操作并行执行
SHOULD use Promise.all for independent operations.
typescript
// CORRECT - parallel
const [users, posts] = await Promise.all([fetchUsers(), fetchPosts()]);
// INEFFICIENT - sequential
const users = await fetchUsers();
const posts = await fetchPosts();推荐使用Promise.all处理独立操作。
typescript
// 正确——并行执行
const [users, posts] = await Promise.all([fetchUsers(), fetchPosts()]);
// 低效——串行执行
const users = await fetchUsers();
const posts = await fetchPosts();4. No Async in Constructors
4. 禁止在构造函数中执行异步操作
MUST NOT do async work in constructors.
typescript
// CORRECT - factory function
class Service {
private constructor(private data: Data) {}
static async create(): Promise<Service> {
const data = await loadData();
return new Service(data);
}
}禁止在构造函数中处理异步任务。
typescript
// 正确——使用工厂函数
class Service {
private constructor(private data: Data) {}
static async create(): Promise<Service> {
const data = await loadData();
return new Service(data);
}
}Enforcement
强制执行方式
- ESLint @typescript-eslint/no-floating-promises
- ESLint require-await
---- ESLint @typescript-eslint/no-floating-promises规则
- ESLint require-await规则
---Creating New Code Rules
创建新的代码规则
mermaid
flowchart TD
A[Identify Pattern] --> B{Category}
B -->|Types| C[typescript/]
B -->|Names| D[naming/]
B -->|Errors| E[errors/]
B -->|Async| F[async/]
B -->|General| G[general/]
B -->|Frontend| H[front/]
B -->|Backend| I[back/]
C --> J[Create Rule Folder]
D --> J
E --> J
F --> J
G --> J
H --> J
I --> J
J --> K[Write rule.md]
K --> L[Add examples.md]
L --> M[Configure Enforcement]
M --> N{Automated?}
N -->|ESLint| O[Add ESLint Rule]
N -->|TypeScript| P[Add tsconfig Option]
N -->|Manual| Q[Add to Review Checklist]
O --> R[Update CI]
P --> R
Q --> S[Announce]
R --> Smermaid
flowchart TD
A[识别模式] --> B{分类}
B -->|类型相关| C[typescript/]
B -->|命名相关| D[naming/]
B -->|错误相关| E[errors/]
B -->|异步相关| F[async/]
B -->|通用规则| G[general/]
B -->|前端相关| H[front/]
B -->|后端相关| I[back/]
C --> J[创建规则目录]
D --> J
E --> J
F --> J
G --> J
H --> J
I --> J
J --> K[编写rule.md]
K --> L[添加examples.md]
L --> M[配置强制执行方式]
M --> N{是否自动化?}
N -->|ESLint| O[添加ESLint规则]
N -->|TypeScript| P[添加tsconfig选项]
N -->|人工| Q[加入评审检查清单]
O --> R[更新CI配置]
P --> R
Q --> S[团队内公告]
R --> SSteps
步骤
- Identify: Find pattern needing standardization
- Categorize: Choose appropriate subfolder
- Create folder:
docs/rules/code/{category}/{rule_name}/ - Write rule.md: Clear rule with rationale and examples
- Add examples.md: Comprehensive correct/incorrect examples
- Configure enforcement: ESLint, TypeScript, or review checklist
- Update CI: Add automated checks
- Announce: Communicate to team
- 识别:找到需要标准化的代码模式
- 分类:选择合适的子目录
- 创建目录:
docs/rules/code/{category}/{rule_name}/ - 编写rule.md:包含清晰的规则、设计初衷和示例
- 添加examples.md:提供全面的正确/错误示例
- 配置强制执行方式:ESLint、TypeScript或评审检查清单
- 更新CI:添加自动化检查
- 公告:向团队成员传达新规则
Signal Files Reference
信号文件参考
| Signal | Type | Content | Purpose |
|---|---|---|---|
| Content | JSON schema version | Track rule version |
| Content | List of tools | Document enforcement |
| Empty | - | Mark as deprecated |
| Content | Path to new rule | Point to replacement |
| Content | ESLint rule name | Link to linter config |
| 信号文件 | 类型 | 内容 | 用途 |
|---|---|---|---|
| 内容文件 | JSON schema版本 | 跟踪规则版本 |
| 内容文件 | 工具列表 | 记录强制执行工具 |
| 空文件 | - | 标记规则已废弃 |
| 内容文件 | 新规则路径 | 指向替代规则 |
| 内容文件 | ESLint规则名称 | 关联代码检查器配置 |
Rule Quality Checklist
规则质量检查清单
Before finalizing a code rule:
- Rule is specific and unambiguous
- Rationale explains the "why"
- Uses RFC 2119 keywords correctly
- At least 2 correct examples
- At least 2 incorrect examples with explanations
- Examples actually compile/run
- Exceptions are documented
- Enforcement mechanism specified
- ESLint rule identified (if applicable)
- Cross-referenced with related rules
在最终确定代码规则前,请检查以下项:
- 规则具体且无歧义
- 说明了设计初衷("为什么")
- 正确使用RFC 2119关键词(MUST/SHOULD等)
- 至少包含2个正确示例
- 至少包含2个错误示例并附带解释
- 示例可实际编译/运行
- 记录了例外情况
- 指定了强制执行机制
- 已关联对应的ESLint规则(如适用)
- 与相关规则进行了交叉引用