general-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

General Best Practices

通用最佳实践

A comprehensive collection of software development best practices applicable across various technology stacks and project types.
本内容是适用于各类技术栈和项目类型的软件开发最佳实践综合合集。

Code Quality

代码质量

Readability and Maintainability

可读性与可维护性

Write short, focused functions with a single responsibility.
Use clear, descriptive names for variables, functions, and classes.
Avoid deep nesting; prefer early returns and guard clauses.
Keep functions and methods to a reasonable length (typically under 30 lines).
编写简短、聚焦单一职责的函数。
为变量、函数和类使用清晰、具有描述性的命名。
避免深层嵌套;优先使用提前返回和守卫子句。
将函数和方法控制在合理长度内(通常不超过30行)。

Error Handling

错误处理

Always handle errors explicitly rather than silently ignoring them.
Use wrapped errors for traceability and context.
Provide meaningful error messages that help with debugging.
Fail fast and fail loudly during development.
始终显式处理错误,而非静默忽略。
使用包装错误以确保可追溯性和上下文信息。
提供有助于调试的有意义错误信息。
开发阶段快速且明确地暴露错误。

Code Organization

代码组织

Organize code into logical modules and packages.
Separate concerns: keep business logic separate from infrastructure code.
Use consistent file and folder naming conventions.
Follow the principle of least surprise in API design.
将代码组织为逻辑模块和包。
关注点分离:将业务逻辑与基础设施代码分开。
使用一致的文件和文件夹命名规范。
API设计遵循最小意外原则。

Architecture

架构

Clean Architecture Principles

整洁架构原则

Structure code into distinct layers:
  • Presentation/Handlers: Handle external requests and responses
  • Application/Services: Orchestrate business operations
  • Domain: Core business logic and entities
  • Infrastructure: External systems, databases, and frameworks
将代码划分为不同层级:
  • Presentation/Handlers(表现层/处理程序):处理外部请求与响应
  • Application/Services(应用层/服务层):编排业务操作
  • Domain(领域层):核心业务逻辑与实体
  • Infrastructure(基础设施层):外部系统、数据库和框架

Design Principles

设计原则

Prefer composition over inheritance.
Program to interfaces, not implementations.
Use dependency injection for testability and flexibility.
Design for change: isolate business logic and minimize framework lock-in.
Apply SOLID principles where appropriate.
优先使用组合而非继承。
面向接口编程,而非面向实现编程。
使用依赖注入提升可测试性和灵活性。
为变更设计:隔离业务逻辑,最小化框架锁定。
在合适的场景下应用SOLID principles。

Testing

测试

Unit Testing

单元测试

Write tests that are fast, isolated, and repeatable.
Use table-driven tests for testing multiple scenarios.
Mock external dependencies cleanly.
Aim for high test coverage of business-critical code.
编写快速、独立且可重复的测试。
使用表驱动测试覆盖多个场景。
合理模拟外部依赖。
针对业务关键代码追求高测试覆盖率。

Integration Testing

集成测试

Test interactions between components and external systems.
Use separate test configurations and databases.
Clean up test data after each test run.
测试组件与外部系统之间的交互。
使用独立的测试配置和数据库。
每次测试运行后清理测试数据。

Test Organization

测试组织

Separate fast unit tests from slower integration tests.
Run fast tests frequently during development.
Include tests in CI/CD pipelines.
将快速的单元测试与较慢的集成测试分开。
开发过程中频繁运行快速测试。
将测试纳入CI/CD流水线。

Security

安全

Input Validation

输入验证

Validate all inputs at service boundaries.
Never trust user input; sanitize and validate everything.
Use parameterized queries to prevent SQL injection.
在服务边界验证所有输入。
绝不信任用户输入;对所有输入进行清理和验证。
使用参数化查询防止SQL注入。

Authentication and Authorization

认证与授权

Use secure defaults for tokens and sessions.
Implement proper access control at every layer.
Store secrets securely; never commit them to version control.
为令牌和会话使用安全默认配置。
在每个层级实现适当的访问控制。
安全存储密钥;绝不要将其提交到版本控制系统。

Network Security

网络安全

Use HTTPS for all communications.
Implement rate limiting to prevent abuse.
Use circuit breakers for external service calls.
所有通信使用HTTPS。
实现速率限制以防止滥用。
为外部服务调用使用断路器模式。

Performance

性能

Optimization Principles

优化原则

Profile before optimizing; avoid premature optimization.
Measure and benchmark regularly.
Focus on hot paths and frequently executed code.
先分析再优化;避免过早优化。
定期进行测量和基准测试。
聚焦于热点路径和频繁执行的代码。

Resource Management

资源管理

Minimize memory allocations in critical paths.
Use connection pooling for database and network connections.
Implement proper resource cleanup and disposal.
在关键路径中最小化内存分配。
为数据库和网络连接使用连接池。
实现适当的资源清理和释放。

Caching

缓存

Cache expensive computations and frequently accessed data.
Use appropriate cache invalidation strategies.
Consider cache consistency and freshness requirements.
缓存计算成本高和频繁访问的数据。
使用合适的缓存失效策略。
考虑缓存一致性和新鲜度要求。

Observability

可观测性

Logging

日志

Use structured logging (JSON format for production).
Include relevant context: request IDs, user IDs, timestamps.
Log at appropriate levels: DEBUG, INFO, WARN, ERROR.
Avoid logging sensitive information.
使用结构化日志(生产环境采用JSON格式)。
包含相关上下文信息:请求ID、用户ID、时间戳。
按适当级别记录日志:DEBUG、INFO、WARN、ERROR。
避免记录敏感信息。

Metrics

指标

Track key metrics: latency, throughput, error rates.
Set up alerts for anomalies and threshold violations.
Use dashboards for visibility into system health.
跟踪关键指标:延迟、吞吐量、错误率。
为异常情况和阈值违规设置告警。
使用仪表板监控系统健康状况。

Tracing

链路追踪

Implement distributed tracing for microservices.
Propagate trace context across service boundaries.
Record important attributes in spans for debugging.
为微服务实现分布式链路追踪。
跨服务边界传播追踪上下文。
在追踪跨度中记录重要属性以便调试。

Documentation

文档

Code Documentation

代码文档

Document public APIs with clear descriptions.
Explain the "why" not just the "what".
Keep documentation close to the code it describes.
Update documentation when code changes.
为公共API编写清晰的描述。
解释“为什么”而非仅仅“是什么”。
将文档与所描述的代码放在一起。
代码变更时同步更新文档。

Project Documentation

项目文档

Maintain a clear README with setup instructions.
Document architecture decisions (ADRs).
Provide contribution guidelines for team members.
维护包含设置说明的清晰README文件。
记录架构决策(ADRs)。
为团队成员提供贡献指南。

Version Control

版本控制

Commit Practices

提交实践

Write clear, concise commit messages.
Make atomic commits that represent a single logical change.
Keep commits small and focused.
编写清晰、简洁的提交信息。
进行原子提交,每个提交代表一个单一逻辑变更。
保持提交内容小而聚焦。

Branch Strategy

分支策略

Use feature branches for new development.
Keep the main branch stable and deployable.
Review code before merging to main.
使用功能分支进行新开发。
保持主分支稳定且可部署。
合并到主分支前进行代码评审。

Tooling and Automation

工具与自动化

Continuous Integration

持续集成

Run tests automatically on every commit.
Enforce code formatting and linting.
Include security scanning in the pipeline.
每次提交自动运行测试。
强制执行代码格式化和代码检查。
在流水线中纳入安全扫描。

Development Environment

开发环境

Use consistent development environments across the team.
Document setup steps and prerequisites.
Automate common development tasks.
在团队内使用一致的开发环境。
记录设置步骤和前置条件。
自动化常见开发任务。