coding-principles

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Language-Agnostic Coding Principles

跨语言编码原则

Core Philosophy

核心理念

  1. Maintainability over Speed: Prioritize long-term code health over initial development velocity
  2. Simplicity First: Choose the simplest solution that meets requirements (YAGNI principle)
  3. Explicit over Implicit: Make intentions clear through code structure and naming
  4. Delete over Comment: Remove unused code instead of commenting it out
  1. 可维护性优先于开发速度:优先考虑代码的长期健康,而非初始开发速度
  2. 简洁至上:选择满足需求的最简方案(YAGNI原则)
  3. 显式优于隐式:通过代码结构与命名清晰传达意图
  4. 删除而非注释:移除未使用的代码,而非将其注释掉

Code Quality

代码质量

Continuous Improvement

持续改进

  • Refactor as you go - don't accumulate technical debt
  • Improve code structure incrementally
  • Keep the codebase lean and focused
  • Delete unused code immediately
  • 边开发边重构——不要积累技术债务
  • 逐步优化代码结构
  • 保持代码库精简且聚焦
  • 立即删除未使用的代码

Readability

可读性

  • Use meaningful, descriptive names drawn from the problem domain
  • Avoid abbreviations unless they are widely recognized
  • Avoid single-letter names except for loop counters or well-known conventions (i, j, x, y)
  • Extract magic numbers and strings into named constants
  • Keep code self-documenting where possible
  • Write code that humans can easily understand
  • 使用源自问题领域的有意义、描述性命名
  • 避免缩写,除非是广泛认可的缩写
  • 避免单字母命名,循环计数器或众所周知的约定(如i, j, x, y)除外
  • 将魔法数字与字符串提取为命名常量
  • 尽可能让代码自文档化
  • 编写人类易于理解的代码

Function Design

函数设计

Parameter Management

参数管理

  • Recommended: 0-2 parameters per function
  • For 3+ parameters: Use objects, structs, or dictionaries to group related parameters
  • Example (conceptual):
    // Instead of: createUser(name, email, age, city, country)
    // Use: createUser(userData)
  • 推荐:每个函数0-2个参数
  • 3个及以上参数:使用对象、结构体或字典对相关参数进行分组
  • 示例(概念性):
    // Instead of: createUser(name, email, age, city, country)
    // Use: createUser(userData)

Single Responsibility

单一职责

  • Each function should do one thing well
  • Keep functions small and focused (typically < 50 lines)
  • Extract complex logic into separate, well-named functions
  • Functions should have a single level of abstraction
  • 每个函数应专注做好一件事
  • 保持函数小巧且聚焦(通常少于50行)
  • 将复杂逻辑提取到单独的、命名清晰的函数中
  • 函数应保持单一抽象层级

Function Organization

函数组织

  • Pure functions when possible (no side effects)
  • Separate data transformation from side effects
  • Use early returns to reduce nesting
  • Avoid deep nesting (maximum 3 levels)
  • 尽可能使用纯函数(无副作用)
  • 将数据转换与副作用分离
  • 使用提前返回减少嵌套
  • 避免深层嵌套(最多3层)

Error Handling

错误处理

Error Management Principles

错误管理原则

  • Always handle errors: Log with context or propagate explicitly
  • Log appropriately: Include context for debugging
  • Protect sensitive data: Mask or exclude passwords, tokens, PII from logs
  • Fail fast: Detect and report errors as early as possible
  • 始终处理错误:附带上下文日志记录或显式传播错误
  • 合理记录日志:包含便于调试的上下文信息
  • 保护敏感数据:在日志中屏蔽或排除密码、令牌、个人可识别信息(PII)
  • 快速失败:尽早检测并报告错误

Error Propagation

错误传播

  • Use language-appropriate error handling mechanisms
  • Propagate errors to appropriate handling levels
  • Provide meaningful error messages
  • Include error context when re-throwing
  • 使用语言对应的错误处理机制
  • 将错误传播到合适的处理层级
  • 提供有意义的错误信息
  • 重新抛出错误时包含错误上下文

Dependency Management

依赖管理

Loose Coupling via Parameterized Dependencies

通过参数化依赖实现松耦合

  • Inject external dependencies as parameters (constructor injection for classes, function parameters for procedural/functional code)
  • Depend on abstractions, not concrete implementations
  • Minimize inter-module dependencies
  • Facilitate testing through mockable dependencies
  • 将外部依赖作为参数注入(类使用构造函数注入,过程式/函数式代码使用函数参数)
  • 依赖抽象而非具体实现
  • 最小化模块间依赖
  • 通过可模拟的依赖简化测试

Performance Considerations

性能考量

Optimization Approach

优化方法

  • Measure first: Profile before optimizing
  • Focus on algorithms: Algorithmic complexity > micro-optimizations
  • Use appropriate data structures: Choose based on access patterns
  • Resource management: Handle memory, connections, and files properly
  • 先测量:优化前先进行性能分析
  • 聚焦算法:算法复杂度优于微优化
  • 使用合适的数据结构:根据访问模式选择
  • 资源管理:正确处理内存、连接与文件

When to Optimize

何时优化

  • After identifying actual bottlenecks
  • When performance issues are measurable
  • Not prematurely during initial development
  • 识别出实际性能瓶颈后
  • 当性能问题可被量化时
  • 不要在初始开发阶段过早优化

Code Organization

代码组织

Structural Principles

结构原则

  • Group related functionality: Keep related code together
  • Separate concerns: Domain logic, data access, presentation
  • Consistent naming: Follow project conventions
  • Module cohesion: High cohesion within modules, low coupling between
  • 相关功能分组:将相关代码放在一起
  • 关注点分离:领域逻辑、数据访问、展示层分离
  • 命名一致性:遵循项目约定
  • 模块内聚性:模块内部高内聚,模块间低耦合

File Organization

文件组织

  • One primary responsibility per file
  • Logical grouping of related functions/classes
  • Clear folder structure reflecting architecture
  • Avoid "god files" (files > 500 lines)
  • 每个文件对应一个主要职责
  • 相关函数/类的逻辑分组
  • 清晰反映架构的文件夹结构
  • 避免“上帝文件”(文件行数超过500行)

Commenting Principles

注释原则

When to Comment

何时注释

  • Document "what": Describe what the code does
  • Explain "why": Clarify reasoning behind decisions
  • Note limitations: Document known constraints or edge cases
  • API documentation: Public interfaces need clear documentation
  • 记录“做什么”:描述代码的功能
  • 解释“为什么”:阐明决策背后的理由
  • 标注限制:记录已知的约束或边缘情况
  • API文档:公共接口需要清晰的文档

When NOT to Comment

何时不注释

  • Avoid describing "how" (the code shows that)
  • Don't include historical information (use version control)
  • Remove commented-out code (use git to retrieve old code)
  • Avoid obvious comments that restate the code
  • 避免描述“怎么做”(代码本身已体现)
  • 不要包含历史信息(使用版本控制)
  • 移除被注释的代码(使用git检索旧代码)
  • 避免显而易见、重复代码内容的注释

Comment Quality

注释质量

  • Keep comments concise and timeless
  • Update comments when changing code
  • Use proper grammar and formatting
  • Write for future maintainers
  • 保持注释简洁且持久
  • 修改代码时同步更新注释
  • 使用正确的语法与格式
  • 为未来的维护者编写注释

Refactoring Approach

重构方法

Safe Refactoring

安全重构

  • Small steps: Make one change at a time
  • Maintain working state: Keep tests passing
  • Verify behavior: Run tests after each change
  • Incremental improvement: Don't aim for perfection immediately
  • 小步迭代:每次只做一处修改
  • 保持可运行状态:确保测试始终通过
  • 验证行为:每次修改后运行测试
  • 逐步改进:不要追求一蹴而就的完美

Refactoring Triggers

重构触发点

  • Code duplication (DRY principle)
  • Functions > 50 lines
  • Complex conditional logic
  • Unclear naming or structure
  • 代码重复(DRY原则)
  • 函数行数超过50行
  • 复杂的条件逻辑
  • 命名或结构不清晰

Testing Considerations

测试考量

Testability

可测试性

  • Write testable code from the start
  • Avoid hidden dependencies
  • Keep side effects explicit
  • Design for parameterized dependencies
  • 从一开始就编写可测试的代码
  • 避免隐藏依赖
  • 显式处理副作用
  • 针对参数化依赖进行设计

Test-Driven Development

测试驱动开发

  • Write tests before implementation when appropriate
  • Keep tests simple and focused
  • Test behavior, not implementation
  • Maintain test quality equal to production code
  • 适当时先编写测试再实现功能
  • 保持测试简洁且聚焦
  • 测试行为而非实现细节
  • 保持测试质量与生产代码相当

Security Principles

安全原则

General Security

通用安全

  • Store secrets in environment variables or secret managers
  • Validate all external input
  • Use parameterized queries for databases
  • Follow principle of least privilege
  • 将密钥存储在环境变量或密钥管理器中
  • 验证所有外部输入
  • 对数据库使用参数化查询
  • 遵循最小权限原则

Data Protection

数据保护

  • Encrypt sensitive data at rest and in transit
  • Sanitize user input
  • Avoid logging sensitive information
  • Use secure random generators for security-critical operations
  • 对静态与传输中的敏感数据进行加密
  • 清理用户输入
  • 避免记录敏感信息
  • 对安全关键操作使用安全随机生成器

Documentation

文档

Code Documentation

代码文档

  • Document public APIs and interfaces
  • Include usage examples for complex functionality
  • Maintain README files for modules
  • Keep documentation in sync with code
  • 为公共API与接口编写文档
  • 为复杂功能包含使用示例
  • 维护模块的README文件
  • 保持文档与代码同步

Architecture Documentation

架构文档

  • Document high-level design decisions
  • Explain integration points
  • Clarify data flows and boundaries
  • Record trade-offs and alternatives considered
  • 记录高层设计决策
  • 解释集成点
  • 阐明数据流与边界
  • 记录权衡与备选方案

Version Control Practices

版本控制实践

Commit Practices

提交实践

  • Make atomic, focused commits
  • Write clear, descriptive commit messages
  • Commit working code (passes tests)
  • Avoid committing debug code or secrets
  • 进行原子化、聚焦的提交
  • 编写清晰、描述性的提交信息
  • 提交可运行的代码(通过测试)
  • 避免提交调试代码或密钥

Code Review Readiness

代码评审准备

  • Self-review before requesting review
  • Keep changes focused and reviewable
  • Provide context in pull request descriptions
  • Respond to feedback constructively
  • 请求评审前先进行自我评审
  • 保持变更聚焦且易于评审
  • 在拉取请求描述中提供上下文
  • 建设性地回应反馈

Language-Specific Adaptations

语言特定适配

While these principles are language-agnostic, adapt them to your specific programming language:
  • Static typing: Use strong types when available
  • Dynamic typing: Add runtime validation
  • OOP languages: Apply SOLID principles
  • Functional languages: Prefer pure functions and immutability
  • Concurrency: Follow language-specific patterns for thread safety
尽管这些原则是跨语言的,但需根据具体编程语言进行适配:
  • 静态类型语言:尽可能使用强类型
  • 动态类型语言:添加运行时验证
  • 面向对象语言:应用SOLID原则
  • 函数式语言:优先使用纯函数与不可变性
  • 并发编程:遵循语言特定的线程安全模式