coding-standards
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCoding Standards Skill
编码规范技能
Level 1: Quick Start (5 minutes)
第一级:快速入门(5分钟)
What You'll Learn
你将学到
Apply essential coding standards for clean, maintainable code that follows industry best practices.
应用核心编码规范,编写符合行业最佳实践的整洁、可维护代码。
Core Principles
核心原则
- Consistency: Follow established style guides (PEP 8, Airbnb, Google)
- Readability: Write self-documenting code with clear naming
- Maintainability: Keep functions small (<50 lines), files focused (<500 lines)
- Quality: Enforce standards with linters and formatters
- 一致性:遵循既定的风格指南(PEP 8、Airbnb、Google)
- 可读性:使用清晰命名编写自文档化代码
- 可维护性:保持函数精简(少于50行)、文件聚焦单一职责(少于500行)
- 质量:通过代码检查器(linters)和格式化工具强制执行规范
Quick Reference
快速参考
python
undefinedpython
undefined✅ Good: Clear naming, single responsibility
✅ 良好示例:命名清晰、单一职责
def calculate_user_discount(user: User, order: Order) -> Decimal:
"""Calculate discount based on user tier and order total."""
if user.tier == "premium":
return order.total * Decimal("0.15")
return order.total * Decimal("0.05")
def calculate_user_discount(user: User, order: Order) -> Decimal:
"""根据用户等级和订单总额计算折扣。"""
if user.tier == "premium":
return order.total * Decimal("0.15")
return order.total * Decimal("0.05")
❌ Bad: Unclear naming, mixed concerns
❌ 不良示例:命名模糊、职责混杂
def calc(u, o):
d = 0.15 if u.t == "p" else 0.05
save_to_db(u, o, d) # Side effect!
return o.t * d
undefineddef calc(u, o):
d = 0.15 if u.t == "p" else 0.05
save_to_db(u, o, d) # 存在副作用!
return o.t * d
undefinedEssential Checklist
核心检查清单
- Follow language-specific style guide
- Use meaningful, descriptive names
- Limit function complexity (cyclomatic < 10)
- Configure linter and formatter
- Add pre-commit hooks
- 遵循语言特定的风格指南
- 使用有意义的描述性命名
- 限制函数复杂度(圈复杂度 < 10)
- 配置代码检查器和格式化工具
- 添加提交前钩子(pre-commit hooks)
Common Pitfalls
常见误区
- Inconsistent naming conventions within a project
- Functions that do too many things
- Missing or outdated documentation
- Skipping code reviews
- 项目内命名约定不一致
- 函数承担过多职责
- 文档缺失或过时
- 跳过代码评审
Level 2: Implementation (30 minutes)
第二级:实践落地(30分钟)
Deep Dive Topics
深度解析主题
1. Code Style and Formatting
1. 代码风格与格式化
Naming Conventions by Language:
typescript
// TypeScript/JavaScript
class UserService {} // PascalCase for classes
const getUserById = () => {} // camelCase for functions
const API_ENDPOINT = "..." // UPPER_SNAKE_CASE for constantspython
undefined各语言命名约定:
typescript
// TypeScript/JavaScript
class UserService {} // 类使用大驼峰命名(PascalCase)
const getUserById = () => {} // 函数使用小驼峰命名(camelCase)
const API_ENDPOINT = "..." // 常量使用大写蛇形命名(UPPER_SNAKE_CASE)python
undefinedPython
Python
class UserService: # PascalCase for classes
def get_user_by_id(): # snake_case for functions
API_ENDPOINT = "..." # UPPER_SNAKE_CASE for constants
**File Organization:**
src/
├── models/ # Data models and types
├── services/ # Business logic (max 500 lines/file)
├── controllers/ # Request handlers
├── utils/ # Shared utilities
└── config/ # Configuration
undefinedclass UserService: # 类使用大驼峰命名(PascalCase)
def get_user_by_id(): # 函数使用小写蛇形命名(snake_case)
API_ENDPOINT = "..." # 常量使用大写蛇形命名(UPPER_SNAKE_CASE)
**文件组织结构:**
src/
├── models/ # 数据模型与类型定义
├── services/ # 业务逻辑(单文件最大500行)
├── controllers/ # 请求处理器
├── utils/ # 共享工具函数
└── config/ # 配置文件
undefined2. Documentation Standards
2. 文档规范
Function Documentation:
typescript
/**
* Calculates the final price after applying discounts and tax.
*
* @param basePrice - The original price before any adjustments
* @param discountRate - Discount as a decimal (0.1 = 10%)
* @param taxRate - Tax rate as a decimal (0.08 = 8%)
* @returns The final price rounded to 2 decimal places
* @throws {ValidationError} If basePrice is negative
*
* @example
* const finalPrice = calculateFinalPrice(100, 0.1, 0.08);
* // Returns 97.20 (100 - 10% discount + 8% tax)
*/
function calculateFinalPrice(
basePrice: number,
discountRate: number,
taxRate: number
): number {
if (basePrice < 0) {
throw new ValidationError("Base price cannot be negative");
}
const discounted = basePrice * (1 - discountRate);
return Math.round(discounted * (1 + taxRate) * 100) / 100;
}函数文档示例:
typescript
/**
* 计算应用折扣和税费后的最终价格。
*
* @param basePrice - 未做任何调整的原始价格
* @param discountRate - 折扣率(小数形式,0.1 代表10%)
* @param taxRate - 税率(小数形式,0.08 代表8%)
* @returns 保留两位小数的最终价格
* @throws {ValidationError} 当basePrice为负数时抛出
*
* @example
* const finalPrice = calculateFinalPrice(100, 0.1, 0.08);
* // 返回97.20(100元减去10%折扣后加8%税费)
*/
function calculateFinalPrice(
basePrice: number,
discountRate: number,
taxRate: number
): number {
if (basePrice < 0) {
throw new ValidationError("基础价格不能为负数");
}
const discounted = basePrice * (1 - discountRate);
return Math.round(discounted * (1 + taxRate) * 100) / 100;
}3. Architecture Patterns
3. 架构模式
SOLID Principles Application:
typescript
// Single Responsibility Principle
class UserRepository {
async findById(id: string): Promise<User> {}
async save(user: User): Promise<void> {}
}
class UserValidator {
validate(user: User): ValidationResult {}
}
// Dependency Injection
class UserService {
constructor(
private readonly repository: UserRepository,
private readonly validator: UserValidator
) {}
async createUser(userData: UserData): Promise<User> {
const validation = this.validator.validate(userData);
if (!validation.isValid) {
throw new ValidationError(validation.errors);
}
return this.repository.save(new User(userData));
}
}SOLID原则应用:
typescript
// 单一职责原则
class UserRepository {
async findById(id: string): Promise<User> {}
async save(user: User): Promise<void> {}
}
class UserValidator {
validate(user: User): ValidationResult {}
}
// 依赖注入
class UserService {
constructor(
private readonly repository: UserRepository,
private readonly validator: UserValidator
) {}
async createUser(userData: UserData): Promise<User> {
const validation = this.validator.validate(userData);
if (!validation.isValid) {
throw new ValidationError(validation.errors);
}
return this.repository.save(new User(userData));
}
}4. Error Handling
4. 错误处理
typescript
// Custom error hierarchy
class ApplicationError extends Error {
constructor(
message: string,
public code: string,
public statusCode: number = 500
) {
super(message);
this.name = this.constructor.name;
}
}
class ValidationError extends ApplicationError {
constructor(message: string, public fields: string[]) {
super(message, "VALIDATION_ERROR", 400);
}
}
// Usage with proper error handling
async function processPayment(payment: Payment): Promise<Result> {
try {
validatePaymentData(payment);
const result = await paymentGateway.charge(payment);
await auditLog.record("payment.success", { paymentId: result.id });
return result;
} catch (error) {
if (error instanceof ValidationError) {
logger.warn("Invalid payment data", { fields: error.fields });
throw error;
}
logger.error("Payment processing failed", { error, payment });
throw new ApplicationError(
"Payment processing failed",
"PAYMENT_ERROR",
502
);
}
}typescript
// 自定义错误层级
class ApplicationError extends Error {
constructor(
message: string,
public code: string,
public statusCode: number = 500
) {
super(message);
this.name = this.constructor.name;
}
}
class ValidationError extends ApplicationError {
constructor(message: string, public fields: string[]) {
super(message, "VALIDATION_ERROR", 400);
}
}
// 正确的错误处理用法
async function processPayment(payment: Payment): Promise<Result> {
try {
validatePaymentData(payment);
const result = await paymentGateway.charge(payment);
await auditLog.record("payment.success", { paymentId: result.id });
return result;
} catch (error) {
if (error instanceof ValidationError) {
logger.warn("支付数据无效", { fields: error.fields });
throw error;
}
logger.error("支付处理失败", { error, payment });
throw new ApplicationError(
"支付处理失败",
"PAYMENT_ERROR",
502
);
}
}Implementation Patterns
实践模式
DRY (Don't Repeat Yourself)
DRY原则(避免重复代码)
typescript
// ❌ Bad: Repeated logic
function calculateEmployeeSalary(employee: Employee): number {
if (employee.type === "full-time") {
return employee.baseSalary * 1.2 + 5000;
}
return employee.baseSalary * 1.2;
}
function calculateContractorPay(contractor: Contractor): number {
return contractor.baseSalary * 1.2;
}
// ✅ Good: Extracted common logic
function applyStandardBonus(baseSalary: number): number {
return baseSalary * 1.2;
}
function calculateEmployeeSalary(employee: Employee): number {
const withBonus = applyStandardBonus(employee.baseSalary);
return employee.type === "full-time" ? withBonus + 5000 : withBonus;
}typescript
// ❌ 不良示例:重复逻辑
function calculateEmployeeSalary(employee: Employee): number {
if (employee.type === "full-time") {
return employee.baseSalary * 1.2 + 5000;
}
return employee.baseSalary * 1.2;
}
function calculateContractorPay(contractor: Contractor): number {
return contractor.baseSalary * 1.2;
}
// ✅ 良好示例:提取公共逻辑
function applyStandardBonus(baseSalary: number): number {
return baseSalary * 1.2;
}
function calculateEmployeeSalary(employee: Employee): number {
const withBonus = applyStandardBonus(employee.baseSalary);
return employee.type === "full-time" ? withBonus + 5000 : withBonus;
}Automation Tools
自动化工具
json
// package.json - Automation setup
{
"scripts": {
"lint": "eslint . --ext .ts,.tsx",
"format": "prettier --write \"**/*.{ts,tsx,json,md}\"",
"type-check": "tsc --noEmit",
"validate": "npm run lint && npm run type-check && npm run test"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{ts,tsx}": ["eslint --fix", "prettier --write"],
"*.{json,md}": ["prettier --write"]
}
}json
// package.json - 自动化配置
{
"scripts": {
"lint": "eslint . --ext .ts,.tsx",
"format": "prettier --write \"**/*.{ts,tsx,json,md}\"",
"type-check": "tsc --noEmit",
"validate": "npm run lint && npm run type-check && npm run test"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{ts,tsx}": ["eslint --fix", "prettier --write"],
"*.{json,md}": ["prettier --write"]
}
}Integration Points
集成关联
- Links to Security Standards for secure coding
- Links to Testing Standards for testable code design
- Links to NIST Compliance for SI-10, SI-11 controls
- 链接至安全规范以了解安全编码
- 链接至测试规范以了解可测试代码设计
- 链接至NIST合规以了解SI-10、SI-11控制要求
Level 3: Mastery (Extended Learning)
第三级:精通进阶(拓展学习)
Advanced Topics
高级主题
1. Performance Optimization Patterns
1. 性能优化模式
Memoization:
typescript
function memoize<T extends (...args: any[]) => any>(fn: T): T {
const cache = new Map<string, ReturnType<T>>();
return ((...args: Parameters<T>) => {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
}) as T;
}
// Usage
const expensiveCalculation = memoize((n: number) => {
// Complex computation
return Array.from({ length: n }, (_, i) => i * i).reduce((a, b) => a + b);
});记忆化(Memoization):
typescript
function memoize<T extends (...args: any[]) => any>(fn: T): T {
const cache = new Map<string, ReturnType<T>>();
return ((...args: Parameters<T>) => {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
}) as T;
}
// 用法
const expensiveCalculation = memoize((n: number) => {
// 复杂计算逻辑
return Array.from({ length: n }, (_, i) => i * i).reduce((a, b) => a + b);
});2. Concurrency Patterns
2. 并发模式
typescript
// Parallel execution with error handling
async function processItemsConcurrently<T, R>(
items: T[],
processor: (item: T) => Promise<R>,
concurrency: number = 5
): Promise<Array<R | Error>> {
const results: Array<R | Error> = [];
const executing: Promise<void>[] = [];
for (const item of items) {
const promise = processor(item)
.then((result) => {
results.push(result);
})
.catch((error) => {
results.push(error);
});
executing.push(promise);
if (executing.length >= concurrency) {
await Promise.race(executing);
executing.splice(
executing.findIndex((p) => p === promise),
1
);
}
}
await Promise.all(executing);
return results;
}typescript
// 带错误处理的并行执行
async function processItemsConcurrently<T, R>(
items: T[],
processor: (item: T) => Promise<R>,
concurrency: number = 5
): Promise<Array<R | Error>> {
const results: Array<R | Error> = [];
const executing: Promise<void>[] = [];
for (const item of items) {
const promise = processor(item)
.then((result) => {
results.push(result);
})
.catch((error) => {
results.push(error);
});
executing.push(promise);
if (executing.length >= concurrency) {
await Promise.race(executing);
executing.splice(
executing.findIndex((p) => p === promise),
1
);
}
}
await Promise.all(executing);
return results;
}3. API Design Best Practices
3. API设计最佳实践
typescript
// RESTful API design
interface ApiResponse<T> {
data: T;
meta: {
timestamp: string;
requestId: string;
};
errors?: ApiError[];
}
// Versioning strategy
app.use("/api/v1", v1Routes);
app.use("/api/v2", v2Routes);
// Pagination standard
interface PaginatedResponse<T> extends ApiResponse<T[]> {
pagination: {
page: number;
pageSize: number;
totalItems: number;
totalPages: number;
};
}typescript
// RESTful API设计
interface ApiResponse<T> {
data: T;
meta: {
timestamp: string;
requestId: string;
};
errors?: ApiError[];
}
// 版本化策略
app.use("/api/v1", v1Routes);
app.use("/api/v2", v2Routes);
// 分页标准
interface PaginatedResponse<T> extends ApiResponse<T[]> {
pagination: {
page: number;
pageSize: number;
totalItems: number;
totalPages: number;
};
}4. Refactoring Strategies
4. 重构策略
Extract Method:
typescript
// Before
function generateReport(data: Data[]): Report {
// 100+ lines of complex logic
const filtered = data.filter(/* complex condition */);
const transformed = filtered.map(/* complex transformation */);
const aggregated = transformed.reduce(/* complex aggregation */);
// More complex logic...
}
// After
function generateReport(data: Data[]): Report {
const filtered = filterRelevantData(data);
const transformed = transformDataForReport(filtered);
const aggregated = aggregateMetrics(transformed);
return formatReport(aggregated);
}提取方法:
typescript
// 重构前
function generateReport(data: Data[]): Report {
// 100+行复杂逻辑
const filtered = data.filter(/* 复杂条件 */);
const transformed = filtered.map(/* 复杂转换 */);
const aggregated = transformed.reduce(/* 复杂聚合 */);
// 更多复杂逻辑...
}
// 重构后
function generateReport(data: Data[]): Report {
const filtered = filterRelevantData(data);
const transformed = transformDataForReport(filtered);
const aggregated = aggregateMetrics(transformed);
return formatReport(aggregated);
}Resources
参考资源
Essential Reading
必读书籍
Tools and Frameworks
工具与框架
- Linters: ESLint, Pylint, RuboCop, Checkstyle
- Formatters: Prettier, Black, gofmt
- Static Analysis: SonarQube, CodeClimate, DeepSource
- Documentation: JSDoc, Sphinx, Doxygen
- 代码检查器:ESLint、Pylint、RuboCop、Checkstyle
- 格式化工具:Prettier、Black、gofmt
- 静态分析:SonarQube、CodeClimate、DeepSource
- 文档工具:JSDoc、Sphinx、Doxygen
Language-Specific Style Guides
各语言风格指南
Templates
模板
Code Review Checklist
代码评审检查清单
markdown
undefinedmarkdown
undefinedCode Review Checklist
代码评审检查清单
Functionality
功能实现
- Code meets requirements
- Edge cases handled
- Error handling comprehensive
- 代码符合需求
- 边界情况已处理
- 错误处理全面
Code Quality
代码质量
- Follows style guide
- Names are clear and descriptive
- Functions are focused (<50 lines)
- No code duplication
- 遵循风格指南
- 命名清晰且具有描述性
- 函数聚焦单一职责(少于50行)
- 无重复代码
Testing
测试覆盖
- Unit tests included
- Tests cover edge cases
- Tests are maintainable
- 包含单元测试
- 测试覆盖边界情况
- 测试用例可维护
Documentation
文档完善
- Public APIs documented
- Complex logic explained
- README updated if needed
- 公共API已文档化
- 复杂逻辑有注释说明
- 必要时已更新README
Security
安全合规
- No hardcoded secrets
- Input validation present
- SQL injection prevented
undefined- 无硬编码密钥
- 存在输入验证
- 已防止SQL注入
undefinedScripts
脚本工具
Complexity Checker
复杂度检查脚本
python
#!/usr/bin/env python3
"""Check cyclomatic complexity of Python files."""
import sys
from radon.complexity import cc_visit
def check_complexity(filename: str, max_complexity: int = 10) -> bool:
"""Check if file exceeds complexity threshold."""
with open(filename) as f:
code = f.read()
results = cc_visit(code)
violations = [r for r in results if r.complexity > max_complexity]
if violations:
print(f"❌ {filename}: Complexity violations found")
for v in violations:
print(f" - {v.name}: complexity {v.complexity} (max {max_complexity})")
return False
print(f"✅ {filename}: All functions within complexity limit")
return True
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: check_complexity.py <file>")
sys.exit(1)
passed = check_complexity(sys.argv[1])
sys.exit(0 if passed else 1)python
#!/usr/bin/env python3
"""检查Python文件的圈复杂度。"""
import sys
from radon.complexity import cc_visit
def check_complexity(filename: str, max_complexity: int = 10) -> bool:
"""检查文件是否超出复杂度阈值。"""
with open(filename) as f:
code = f.read()
results = cc_visit(code)
violations = [r for r in results if r.complexity > max_complexity]
if violations:
print(f"❌ {filename}: 发现复杂度违规")
for v in violations:
print(f" - {v.name}: 复杂度 {v.complexity}(最大值 {max_complexity})")
return False
print(f"✅ {filename}: 所有函数均在复杂度限制内")
return True
if __name__ == "__main__":
if len(sys.argv) < 2:
print("用法: check_complexity.py <文件路径>")
sys.exit(1)
passed = check_complexity(sys.argv[1])
sys.exit(0 if passed else 1)Examples
示例
Basic Usage
基础用法
python
// TODO: Add basic example for coding-standards
// This example demonstrates core functionalitypython
// TODO: 添加编码规范基础示例
// 本示例展示核心功能Advanced Usage
进阶用法
python
// TODO: Add advanced example for coding-standards
// This example shows production-ready patternspython
// TODO: 添加编码规范进阶示例
// 本示例展示生产级可用模式Integration Example
集成示例
python
// TODO: Add integration example showing how coding-standards
// works with other systems and servicesSee for complete working examples.
examples/coding-standards/python
// TODO: 添加集成示例,展示编码规范如何
// 与其他系统和服务协同工作完整的可运行示例请查看 目录。
examples/coding-standards/Integration Points
集成关联
This skill integrates with:
本技能可与以下内容集成:
Upstream Dependencies
上游依赖
- Tools: Common development tools and frameworks
- Prerequisites: Basic understanding of general concepts
- 工具:通用开发工具与框架
- 前置要求:对通用概念有基本理解
Downstream Consumers
下游应用
- Applications: Production systems requiring coding-standards functionality
- CI/CD Pipelines: Automated testing and deployment workflows
- Monitoring Systems: Observability and logging platforms
- 业务系统:需要编码规范能力的生产系统
- CI/CD流水线:自动化测试与部署工作流
- 监控系统:可观测性与日志平台
Related Skills
相关技能
- See other skills in this category
- 查看本分类下的其他技能
Common Integration Patterns
常见集成模式
- Development Workflow: How this skill fits into daily development
- Production Deployment: Integration with production systems
- Monitoring & Alerting: Observability integration points
- 开发工作流:本技能如何融入日常开发流程
- 生产部署:与生产系统的集成方式
- 监控与告警:可观测性集成点
Common Pitfalls
常见误区
Pitfall 1: Insufficient Testing
误区1:测试不充分
Problem: Not testing edge cases and error conditions leads to production bugs
Solution: Implement comprehensive test coverage including:
- Happy path scenarios
- Error handling and edge cases
- Integration points with external systems
Prevention: Enforce minimum code coverage (80%+) in CI/CD pipeline
问题:未测试边界情况和错误场景导致生产环境出现Bug
解决方案:实现全面的测试覆盖,包括:
- 正常流程场景
- 错误处理与边界情况
- 与外部系统的集成点
预防措施:在CI/CD流水线中强制执行最低代码覆盖率要求(80%+)
Pitfall 2: Hardcoded Configuration
误区2:硬编码配置
Problem: Hardcoding values makes applications inflexible and environment-dependent
Solution: Use environment variables and configuration management:
- Separate config from code
- Use environment-specific configuration files
- Never commit secrets to version control
Prevention: Use tools like dotenv, config validators, and secret scanners
问题:硬编码值导致应用灵活性差,依赖特定环境
解决方案:使用环境变量和配置管理工具:
- 配置与代码分离
- 使用环境特定的配置文件
- 绝对不要将密钥提交至版本控制系统
预防措施:使用dotenv、配置验证工具和密钥扫描工具
Pitfall 3: Ignoring Security Best Practices
误区3:忽略安全最佳实践
Problem: Security vulnerabilities from not following established security patterns
Solution: Follow security guidelines:
- Input validation and sanitization
- Proper authentication and authorization
- Encrypted data transmission (TLS/SSL)
- Regular security audits and updates
Prevention: Use security linters, SAST tools, and regular dependency updates
Best Practices:
- Follow established patterns and conventions for coding-standards
- Keep dependencies up to date and scan for vulnerabilities
- Write comprehensive documentation and inline comments
- Use linting and formatting tools consistently
- Implement proper error handling and logging
- Regular code reviews and pair programming
- Monitor production metrics and set up alerts
问题:未遵循既定安全模式导致安全漏洞
解决方案:遵循安全指南:
- 输入验证与清理
- 正确的身份认证与授权
- 加密数据传输(TLS/SSL)
- 定期安全审计与更新
预防措施:使用安全代码检查器、静态应用安全测试(SAST)工具,并定期更新依赖
最佳实践总结:
- 遵循已确立的编码规范与约定
- 保持依赖更新并扫描漏洞
- 编写全面的文档与内联注释
- 持续使用代码检查器和格式化工具
- 实现完善的错误处理与日志记录
- 定期进行代码评审与结对编程
- 监控生产环境指标并设置告警
Bundled Resources
附带资源
- Full CODING_STANDARDS.md
- UNIFIED_STANDARDS.md
- Example linter configs in
./resources/ - Pre-commit hook templates in
./templates/ - Complexity checking scripts in
./scripts/
- 完整编码规范文档
- 统一规范文档
- 目录下的示例代码检查器配置
./resources/ - 目录下的提交前钩子模板
./templates/ - 目录下的复杂度检查脚本
./scripts/