code-styleguide
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode Styleguide
代码风格指南
Overview
概述
Universal code style guidelines that promote clean, maintainable, and readable code across all programming languages. These principles focus on simplicity, clarity, and avoiding unnecessary complexity while following proven software engineering best practices.
适用于所有编程语言的通用代码风格指南,旨在打造清晰、可维护且易读的代码。这些原则聚焦于简洁性、清晰度,遵循经过验证的软件工程最佳实践,同时避免不必要的复杂性。
Core Principles
核心原则
1. KISS (Keep It Simple, Stupid)
1. KISS(保持简单)
The simplest solution is usually the best solution.
- Favor clear, straightforward code over clever tricks
- One function should do one thing well
- Prefer explicit code over implicit behavior
- Avoid premature optimization
- Write code, not documentation: minimize auxiliary files
- Never use emoji in code or comments
Good:
python
def calculate_total_price(items):
total = 0
for item in items:
total += item.price
return totalAvoid:
python
def calculate_total_price(items):
return sum(item.price for item in items) if items else 0 or reduce(lambda x, y: x + y.price, items, 0)最简单的解决方案通常是最佳方案。
- 优先选择清晰、直接的代码,而非巧妙的技巧
- 一个函数应只做好一件事
- 优先使用显式代码,避免隐式行为
- 避免过早优化
- 编写代码而非文档:尽量减少辅助文件
- 切勿在代码或注释中使用表情符号
良好示例:
python
def calculate_total_price(items):
total = 0
for item in items:
total += item.price
return total应避免:
python
def calculate_total_price(items):
return sum(item.price for item in items) if items else 0 or reduce(lambda x, y: x + y.price, items, 0)2. Abstraction Levels
2. 抽象层级
Each level of abstraction should be consistent and purposeful.
- Functions should operate at a single level of abstraction
- Hide complexity behind clear interfaces
- Use descriptive names that match the abstraction level
Good:
python
def process_user_registration():
user_data = validate_input()
user = create_user(user_data)
send_welcome_email(user)
return userAvoid mixing abstraction levels:
python
def process_user_registration():
if not email or '@' not in email: # Low-level validation
raise ValueError("Invalid email")
user = User.create(email) # High-level operation
smtp.send(email, "Welcome!") # Medium-level operation每个抽象层级应保持一致且具备明确目的性。
- 函数应在单一抽象层级上运作
- 通过清晰的接口隐藏复杂性
- 使用与抽象层级匹配的描述性命名
良好示例:
python
def process_user_registration():
user_data = validate_input()
user = create_user(user_data)
send_welcome_email(user)
return user应避免混合抽象层级:
python
def process_user_registration():
if not email or '@' not in email: # 低层级验证
raise ValueError("Invalid email")
user = User.create(email) # 高层级操作
smtp.send(email, "Welcome!") # 中层级操作3. SOLID Principles
3. SOLID原则
Single Responsibility Principle (SRP)
单一职责原则(SRP)
A class should have one, and only one, reason to change.
python
undefined一个类应该只有一个引起变化的原因。
python
undefinedGood: Separate concerns
良好示例:分离关注点
class User:
def init(self, email, password):
self.email = email
self.password = password
class UserValidator:
def validate_email(self, email):
return '@' in email and '.' in email
class EmailService:
def send_welcome_email(self, user):
# Email sending logic
undefinedclass User:
def init(self, email, password):
self.email = email
self.password = password
class UserValidator:
def validate_email(self, email):
return '@' in email and '.' in email
class EmailService:
def send_welcome_email(self, user):
# 邮件发送逻辑
undefinedOpen/Closed Principle (OCP)
开放/封闭原则(OCP)
Classes should be open for extension, closed for modification.
python
undefined类应对扩展开放,对修改封闭。
python
undefinedGood: Use abstract base classes
良好示例:使用抽象基类
from abc import ABC, abstractmethod
class PaymentProcessor(ABC):
@abstractmethod
def process_payment(self, amount):
pass
class CreditCardProcessor(PaymentProcessor):
def process_payment(self, amount):
# Credit card processing logic
class PayPalProcessor(PaymentProcessor):
def process_payment(self, amount):
# PayPal processing logic
undefinedfrom abc import ABC, abstractmethod
class PaymentProcessor(ABC):
@abstractmethod
def process_payment(self, amount):
pass
class CreditCardProcessor(PaymentProcessor):
def process_payment(self, amount):
# 信用卡处理逻辑
class PayPalProcessor(PaymentProcessor):
def process_payment(self, amount):
# PayPal处理逻辑
undefinedLiskov Substitution Principle (LSP)
里氏替换原则(LSP)
Objects of a superclass should be replaceable with objects of a subclass.
父类对象应可被子类对象替换,且不影响程序的正确性。
Interface Segregation Principle (ISP)
接口隔离原则(ISP)
Clients should not be forced to depend on interfaces they don't use.
客户端不应被迫依赖其不需要的接口。
Dependency Inversion Principle (DIP)
依赖倒置原则(DIP)
Depend on abstractions, not concretions.
依赖于抽象,而非具体实现。
4. Avoiding Over-Engineering
4. 避免过度设计
Don't build what you don't need right now.
- Start with the simplest solution that works
- Add complexity only when requirements demand it
- Prefer composition over inheritance
- Avoid speculative generality
- Question every abstraction: does it solve a real problem?
- Resist the urge to make code "flexible" without concrete use cases
Good (simple and direct):
python
class ConfigManager:
def __init__(self, config_file):
with open(config_file) as f:
self.config = json.load(f)
def get(self, key):
return self.config.get(key)Over-engineered:
python
class AbstractConfigurationStrategy(ABC):
@abstractmethod
def load_configuration(self): pass
class JSONConfigurationStrategy(AbstractConfigurationStrategy):
# ... complex factory pattern implementation
class ConfigurationManager:
def __init__(self, strategy: AbstractConfigurationStrategy):
self.strategy = strategy
# ... unnecessary abstractions for a simple config reader不要构建当前不需要的功能。
- 从能满足需求的最简单方案入手
- 仅在需求明确要求时才增加复杂性
- 优先使用组合而非继承
- 避免无根据的通用性设计
- 质疑每一处抽象:它是否解决了实际问题?
- 不要在没有具体用例的情况下强行让代码“灵活”
良好示例(简单直接):
python
class ConfigManager:
def __init__(self, config_file):
with open(config_file) as f:
self.config = json.load(f)
def get(self, key):
return self.config.get(key)过度设计示例:
python
class AbstractConfigurationStrategy(ABC):
@abstractmethod
def load_configuration(self): pass
class JSONConfigurationStrategy(AbstractConfigurationStrategy):
# ... 复杂的工厂模式实现
class ConfigurationManager:
def __init__(self, strategy: AbstractConfigurationStrategy):
self.strategy = strategy
# ... 针对简单配置读取器的不必要抽象5. Minimize Documentation Files
5. 最小化文档文件
Code should be self-documenting. Documentation is supplementary, not primary.
- Avoid creating multiple CHANGELOG, or summary files
- Don't generate progress reports or status documents
- Keep documentation in code (docstrings, inline comments)
- One README per project maximum
- No emoji in any output files
Good:
python
def calculate_discount(price: float, customer_type: str) -> float:
"""Calculate discount based on customer type.
Args:
price: Original price
customer_type: One of 'regular', 'premium', 'vip'
Returns:
Discounted price
"""
discounts = {'regular': 0, 'premium': 0.1, 'vip': 0.2}
return price * (1 - discounts.get(customer_type, 0))Avoid:
- CHANGES.md documenting every modification
- SUMMARY.md repeating what code already shows
- Multiple README files at different levels
- Using emoji for status indicators or decorative purposes
代码应具备自解释性。文档是补充,而非核心。
- 避免创建多个CHANGELOG或摘要文件
- 不要生成进度报告或状态文档
- 将文档保留在代码中(文档字符串、行内注释)
- 每个项目最多保留一个README文件
- 任何输出文件中均不得使用表情符号
良好示例:
python
def calculate_discount(price: float, customer_type: str) -> float:
"""根据客户类型计算折扣。
参数:
price: 原价
customer_type: 可选值为'regular'、'premium'、'vip'
返回:
折扣后的价格
"""
discounts = {'regular': 0, 'premium': 0.1, 'vip': 0.2}
return price * (1 - discounts.get(customer_type, 0))应避免:
- 记录每一处修改的CHANGES.md
- 重复代码已有信息的SUMMARY.md
- 不同层级的多个README文件
- 使用表情符号作为状态标识或装饰
Naming Conventions
命名规范
Universal Rules
通用规则
- Use descriptive, searchable names
- Avoid abbreviations and single-character variables (except loop counters)
- Use intention-revealing names
- Avoid mental mapping
Good:
python
user_count = len(users)
is_valid_email = validate_email(email)
for user_index in range(user_count):Avoid:
python
uc = len(u)
flag = check(e)
for i in range(uc):- 使用描述性、便于搜索的名称
- 避免缩写和单字符变量(循环计数器除外)
- 使用能体现意图的名称
- 避免需要读者自行联想的命名
良好示例:
python
user_count = len(users)
is_valid_email = validate_email(email)
for user_index in range(user_count):应避免:
python
uc = len(u)
flag = check(e)
for i in range(uc):Functions and Methods
函数与方法
- Use verb phrases for actions
- Use boolean-returning functions with ,
is_,has_prefixescan_ - Keep function names concise but descriptive
- 使用动词短语命名动作类函数
- 返回布尔值的函数使用、
is_、has_前缀can_ - 函数名称应简洁且具备描述性
Variables
变量
- Use noun phrases for objects
- Use descriptive names for important variables
- Use conventional names for temporary variables
- 使用名词短语命名对象
- 为重要变量使用描述性名称
- 临时变量使用常规命名
Constants
常量
- Use UPPER_SNAKE_CASE for constants
- Make the purpose clear from the name
- 常量使用大写蛇形命名法(UPPER_SNAKE_CASE)
- 名称需清晰体现常量用途
Code Organization
代码组织
File Structure
文件结构
- One class per file (when practical)
- Group related functions together
- Separate concerns into different modules/packages
- Use consistent directory structures
- 一个文件对应一个类(在可行的情况下)
- 将相关函数分组
- 按关注点拆分到不同模块/包中
- 使用一致的目录结构
Function Design
函数设计
- Keep functions small (generally under 20 lines)
- Single responsibility per function
- Minimize function parameters (ideally ≤ 3)
- Avoid deep nesting (prefer early returns)
Good:
python
def process_order(order):
if not order.is_valid():
return None
if not order.has_payment():
return None
return fulfill_order(order)Avoid:
python
def process_order(order):
if order.is_valid():
if order.has_payment():
# deep nesting continues...
return fulfill_order(order)
else:
return None
else:
return None- 保持函数短小(通常不超过20行)
- 每个函数单一职责
- 尽量减少函数参数(理想情况下≤3个)
- 避免深层嵌套(优先使用提前返回)
良好示例:
python
def process_order(order):
if not order.is_valid():
return None
if not order.has_payment():
return None
return fulfill_order(order)应避免:
python
def process_order(order):
if order.is_valid():
if order.has_payment():
# 深层嵌套持续...
return fulfill_order(order)
else:
return None
else:
return NoneError Handling
错误处理
- Fail fast and fail clearly
- Use specific exception types
- Provide meaningful error messages
- Handle errors at appropriate levels
python
undefined- 快速失败且清晰报错
- 使用特定的异常类型
- 提供有意义的错误信息
- 在合适的层级处理错误
python
undefinedGood: Specific and clear
良好示例:特定且清晰
class InvalidEmailError(ValueError):
def init(self, email):
super().init(f"Invalid email format: {email}")
def validate_email(email):
if '@' not in email:
raise InvalidEmailError(email)
undefinedclass InvalidEmailError(ValueError):
def init(self, email):
super().init(f"Invalid email format: {email}")
def validate_email(email):
if '@' not in email:
raise InvalidEmailError(email)
undefinedComments and Documentation
注释与文档
Write self-documenting code first. Documentation lives in the code.
- Code readability reduces documentation needs
- Comment the "why", not the "what"
- Keep comments up-to-date or remove them
- Use docstrings for public APIs
- Never use emoji in comments or documentation
- Avoid creating separate documentation files
Good comments explain intent:
python
undefined优先编写自解释代码。文档应内嵌于代码中。
- 代码可读性越高,对文档的需求就越少
- 注释应解释“为什么”,而非“是什么”
- 保持注释更新或过时即删除
- 公共API使用文档字符串
- 切勿在注释或文档中使用表情符号
- 避免创建独立的文档文件
良好注释:解释意图
python
undefinedRetry up to 3 times to handle transient network issues
最多重试3次以处理临时网络问题
def fetch_user_data(user_id, max_retries=3):
**Avoid obvious comments:**
```pythondef fetch_user_data(user_id, max_retries=3):
**应避免显而易见的注释:**
```pythonIncrement counter by 1
将计数器加1
counter += 1
**Avoid emoji decorations:**
```pythoncounter += 1
**应避免表情符号装饰:**
```pythonBad: Don't do this
不良示例:请勿这样做
✅ Success! This function works!
✅ Success! This function works!
🚀 Super fast implementation
🚀 Super fast implementation
⚠️ Warning: Check this
⚠️ Warning: Check this
Good: Clear, professional comments
良好示例:清晰、专业的注释
Returns None if validation fails
验证失败时返回None
Optimized for large datasets
针对大型数据集优化
Validates input before processing
处理前先验证输入
undefinedundefinedTesting Principles
测试原则
- Write tests that document expected behavior
- Test behavior, not implementation
- Keep tests simple and focused
- Use descriptive test names
python
def test_should_reject_user_with_invalid_email():
invalid_email = "not-an-email"
with pytest.raises(InvalidEmailError):
create_user(email=invalid_email)- 编写能记录预期行为的测试
- 测试行为而非实现细节
- 保持测试简单且聚焦
- 使用描述性的测试名称
python
def test_should_reject_user_with_invalid_email():
invalid_email = "not-an-email"
with pytest.raises(InvalidEmailError):
create_user(email=invalid_email)When to Apply These Guidelines
何时应用这些指南
Use this skill when:
- Writing new code in any language
- Reviewing code (yours or others')
- Refactoring existing code
- Establishing team coding standards
- Teaching code quality principles
- Deciding between multiple implementation approaches
Key decision points:
- Is this the simplest solution that meets the requirements?
- Does each component have a single, clear responsibility?
- Would a new team member understand this code?
- Am I building for current needs or speculative future needs?
- Am I creating unnecessary documentation files?
- Is my code simple enough to not need separate explanatory documents?
在以下场景使用本指南:
- 用任意语言编写新代码时
- 评审代码(自己或他人的)时
- 重构现有代码时
- 建立团队编码标准时
- 教授代码质量原则时
- 在多种实现方案间做决策时
关键决策要点:
- 这是满足需求的最简单方案吗?
- 每个组件是否具备单一、清晰的职责?
- 新团队成员能理解这段代码吗?
- 我是在为当前需求还是推测性的未来需求构建功能?
- 我是否创建了不必要的文档文件?
- 我的代码是否足够简单,无需单独的说明文档?
Output Guidelines
输出规范
When generating or modifying code:
-
Minimize file generation:
- Create only essential code files
- Avoid generating summary or changelog files
- Don't create duplicate documentation
-
No emoji in output:
- Code files: absolutely no emoji
- Comments: use plain text only
- Documentation: professional language only
- Log messages: text-based indicators only
-
Self-documenting code over documents:
- Prefer clear naming over explanatory comments
- Prefer docstrings over separate API docs
- Prefer type hints over type documentation
Good output structure:
project/
├── src/
│ ├── main.py # Main code
│ └── utils.py # Helper functions
├── tests/
│ └── test_main.py # Tests
└── README.md # One README onlyAvoid:
project/
├── src/
│ ├── main.py
│ └── utils.py
├── docs/
│ ├── CHANGES.md # Unnecessary
│ ├── SUMMARY.md # Unnecessary
│ └── API_GUIDE.md # Unnecessary
├── README.md
└── NOTES.md # Unnecessary生成或修改代码时:
-
最小化文件生成:
- 仅创建必要的代码文件
- 避免生成摘要或变更日志文件
- 不要创建重复的文档
-
输出中禁止使用表情符号:
- 代码文件:绝对禁止使用表情符号
- 注释:仅使用纯文本
- 文档:仅使用专业语言
- 日志消息:仅使用基于文本的标识
-
优先自解释代码而非文档:
- 优先使用清晰命名而非解释性注释
- 优先使用文档字符串而非独立API文档
- 优先使用类型提示而非类型文档
良好的输出结构:
project/
├── src/
│ ├── main.py # 主代码
│ └── utils.py # 辅助函数
├── tests/
│ └── test_main.py # 测试代码
└── README.md # 仅保留一个README应避免:
project/
├── src/
│ ├── main.py
│ └── utils.py
├── docs/
│ ├── CHANGES.md # 不必要
│ ├── SUMMARY.md # 不必要
│ └── API_GUIDE.md # 不必要
├── README.md
└── NOTES.md # 不必要