软件工程:程序设计风格

📌目录



⚖️ 程序设计风格:从能用到优雅

程序设计风格是程序员在编写代码时遵循的一系列规范和习惯。良好的程序设计风格不仅能提高代码的可读性和可维护性,还能减少错误、提高开发效率。本文将详细介绍程序设计风格的原则、规范和最佳实践。

🎯 一、程序设计风格概述

(一)程序设计风格的定义

程序设计风格是指程序员在编写代码时遵循的一系列规范和习惯,包括命名规范、代码格式、注释风格、结构组织等方面。

程序设计风格概念
#mermaid-svg-Kyo1IYA77t4dnZEZ{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-Kyo1IYA77t4dnZEZ .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-Kyo1IYA77t4dnZEZ .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-Kyo1IYA77t4dnZEZ .error-icon{fill:#552222;}#mermaid-svg-Kyo1IYA77t4dnZEZ .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-Kyo1IYA77t4dnZEZ .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-Kyo1IYA77t4dnZEZ .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-Kyo1IYA77t4dnZEZ .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-Kyo1IYA77t4dnZEZ .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-Kyo1IYA77t4dnZEZ .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-Kyo1IYA77t4dnZEZ .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-Kyo1IYA77t4dnZEZ .marker{fill:#333333;stroke:#333333;}#mermaid-svg-Kyo1IYA77t4dnZEZ .marker.cross{stroke:#333333;}#mermaid-svg-Kyo1IYA77t4dnZEZ svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-Kyo1IYA77t4dnZEZ p{margin:0;}#mermaid-svg-Kyo1IYA77t4dnZEZ .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-Kyo1IYA77t4dnZEZ .cluster-label text{fill:#333;}#mermaid-svg-Kyo1IYA77t4dnZEZ .cluster-label span{color:#333;}#mermaid-svg-Kyo1IYA77t4dnZEZ .cluster-label span p{background-color:transparent;}#mermaid-svg-Kyo1IYA77t4dnZEZ .label text,#mermaid-svg-Kyo1IYA77t4dnZEZ span{fill:#333;color:#333;}#mermaid-svg-Kyo1IYA77t4dnZEZ .node rect,#mermaid-svg-Kyo1IYA77t4dnZEZ .node circle,#mermaid-svg-Kyo1IYA77t4dnZEZ .node ellipse,#mermaid-svg-Kyo1IYA77t4dnZEZ .node polygon,#mermaid-svg-Kyo1IYA77t4dnZEZ .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-Kyo1IYA77t4dnZEZ .rough-node .label text,#mermaid-svg-Kyo1IYA77t4dnZEZ .node .label text,#mermaid-svg-Kyo1IYA77t4dnZEZ .image-shape .label,#mermaid-svg-Kyo1IYA77t4dnZEZ .icon-shape .label{text-anchor:middle;}#mermaid-svg-Kyo1IYA77t4dnZEZ .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-Kyo1IYA77t4dnZEZ .rough-node .label,#mermaid-svg-Kyo1IYA77t4dnZEZ .node .label,#mermaid-svg-Kyo1IYA77t4dnZEZ .image-shape .label,#mermaid-svg-Kyo1IYA77t4dnZEZ .icon-shape .label{text-align:center;}#mermaid-svg-Kyo1IYA77t4dnZEZ .node.clickable{cursor:pointer;}#mermaid-svg-Kyo1IYA77t4dnZEZ .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-Kyo1IYA77t4dnZEZ .arrowheadPath{fill:#333333;}#mermaid-svg-Kyo1IYA77t4dnZEZ .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-Kyo1IYA77t4dnZEZ .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-Kyo1IYA77t4dnZEZ .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-Kyo1IYA77t4dnZEZ .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-Kyo1IYA77t4dnZEZ .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-Kyo1IYA77t4dnZEZ .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-Kyo1IYA77t4dnZEZ .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-Kyo1IYA77t4dnZEZ .cluster text{fill:#333;}#mermaid-svg-Kyo1IYA77t4dnZEZ .cluster span{color:#333;}#mermaid-svg-Kyo1IYA77t4dnZEZ div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-Kyo1IYA77t4dnZEZ .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-Kyo1IYA77t4dnZEZ rect.text{fill:none;stroke-width:0;}#mermaid-svg-Kyo1IYA77t4dnZEZ .icon-shape,#mermaid-svg-Kyo1IYA77t4dnZEZ .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-Kyo1IYA77t4dnZEZ .icon-shape p,#mermaid-svg-Kyo1IYA77t4dnZEZ .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-Kyo1IYA77t4dnZEZ .icon-shape .label rect,#mermaid-svg-Kyo1IYA77t4dnZEZ .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-Kyo1IYA77t4dnZEZ .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-Kyo1IYA77t4dnZEZ .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-Kyo1IYA77t4dnZEZ :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 程序设计风格
命名规范
代码格式
注释风格
结构组织
编程习惯
变量、函数、类
缩进、空格、换行
文档注释、行注释
模块化、层次化
简洁、清晰

(二)程序设计风格的重要性

程序设计风格重要性

方面 说明
可读性 提高代码可读性
可维护性 便于维护和修改
协作效率 提高团队协作效率
代码质量 减少错误,提高质量
开发效率 提高开发效率

(三)程序设计风格的原则

程序设计风格原则
#mermaid-svg-tTONZznH5ZqhwE2A{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-tTONZznH5ZqhwE2A .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-tTONZznH5ZqhwE2A .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-tTONZznH5ZqhwE2A .error-icon{fill:#552222;}#mermaid-svg-tTONZznH5ZqhwE2A .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-tTONZznH5ZqhwE2A .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-tTONZznH5ZqhwE2A .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-tTONZznH5ZqhwE2A .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-tTONZznH5ZqhwE2A .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-tTONZznH5ZqhwE2A .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-tTONZznH5ZqhwE2A .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-tTONZznH5ZqhwE2A .marker{fill:#333333;stroke:#333333;}#mermaid-svg-tTONZznH5ZqhwE2A .marker.cross{stroke:#333333;}#mermaid-svg-tTONZznH5ZqhwE2A svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-tTONZznH5ZqhwE2A p{margin:0;}#mermaid-svg-tTONZznH5ZqhwE2A .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-tTONZznH5ZqhwE2A .cluster-label text{fill:#333;}#mermaid-svg-tTONZznH5ZqhwE2A .cluster-label span{color:#333;}#mermaid-svg-tTONZznH5ZqhwE2A .cluster-label span p{background-color:transparent;}#mermaid-svg-tTONZznH5ZqhwE2A .label text,#mermaid-svg-tTONZznH5ZqhwE2A span{fill:#333;color:#333;}#mermaid-svg-tTONZznH5ZqhwE2A .node rect,#mermaid-svg-tTONZznH5ZqhwE2A .node circle,#mermaid-svg-tTONZznH5ZqhwE2A .node ellipse,#mermaid-svg-tTONZznH5ZqhwE2A .node polygon,#mermaid-svg-tTONZznH5ZqhwE2A .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-tTONZznH5ZqhwE2A .rough-node .label text,#mermaid-svg-tTONZznH5ZqhwE2A .node .label text,#mermaid-svg-tTONZznH5ZqhwE2A .image-shape .label,#mermaid-svg-tTONZznH5ZqhwE2A .icon-shape .label{text-anchor:middle;}#mermaid-svg-tTONZznH5ZqhwE2A .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-tTONZznH5ZqhwE2A .rough-node .label,#mermaid-svg-tTONZznH5ZqhwE2A .node .label,#mermaid-svg-tTONZznH5ZqhwE2A .image-shape .label,#mermaid-svg-tTONZznH5ZqhwE2A .icon-shape .label{text-align:center;}#mermaid-svg-tTONZznH5ZqhwE2A .node.clickable{cursor:pointer;}#mermaid-svg-tTONZznH5ZqhwE2A .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-tTONZznH5ZqhwE2A .arrowheadPath{fill:#333333;}#mermaid-svg-tTONZznH5ZqhwE2A .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-tTONZznH5ZqhwE2A .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-tTONZznH5ZqhwE2A .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-tTONZznH5ZqhwE2A .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-tTONZznH5ZqhwE2A .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-tTONZznH5ZqhwE2A .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-tTONZznH5ZqhwE2A .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-tTONZznH5ZqhwE2A .cluster text{fill:#333;}#mermaid-svg-tTONZznH5ZqhwE2A .cluster span{color:#333;}#mermaid-svg-tTONZznH5ZqhwE2A div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-tTONZznH5ZqhwE2A .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-tTONZznH5ZqhwE2A rect.text{fill:none;stroke-width:0;}#mermaid-svg-tTONZznH5ZqhwE2A .icon-shape,#mermaid-svg-tTONZznH5ZqhwE2A .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-tTONZznH5ZqhwE2A .icon-shape p,#mermaid-svg-tTONZznH5ZqhwE2A .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-tTONZznH5ZqhwE2A .icon-shape .label rect,#mermaid-svg-tTONZznH5ZqhwE2A .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-tTONZznH5ZqhwE2A .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-tTONZznH5ZqhwE2A .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-tTONZznH5ZqhwE2A :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 设计原则
清晰性
简洁性
一致性
可读性
可维护性
意图清晰
代码简洁
风格统一
易于阅读
易于维护

📦 二、命名规范

(一)命名原则

命名原则

原则 说明
见名知意 名称能表达含义
一致性 保持命名风格一致
简洁性 名称简洁明了
规范性 遵循语言规范

(二)变量命名

变量命名规范

规范 说明 示例
有意义 表达变量含义 user_name
小写字母 使用小写字母 count
下划线分隔 单词间用下划线 total_score
避免缩写 除非通用缩写 student_id

变量命名示例

python 复制代码
# 好的变量命名
user_name = "Alice"          # 见名知意
total_score = 95             # 清晰表达
max_retry_count = 3          # 完整表达
is_valid = True              # 布尔变量用is_前缀

# 不好的变量命名
n = "Alice"                  # 无意义
x = 95                       # 无意义
cnt = 3                      # 缩写不清晰
flag = True                  # 含义不明

# 变量命名最佳实践
# 1. 使用完整的单词
first_name = "张"
last_name = "三"
email_address = "zhangsan@example.com"

# 2. 布尔变量使用is/has/can等前缀
is_active = True
has_permission = False
can_edit = True

# 3. 集合变量使用复数
users = ["Alice", "Bob"]
products = []
order_items = {}

# 4. 常量使用大写
MAX_CONNECTIONS = 100
DEFAULT_TIMEOUT = 30
API_BASE_URL = "https://api.example.com"

# 5. 避免使用单字母变量(循环变量除外)
# 不好
a = 10
b = 20
c = a + b

# 好
width = 10
height = 20
area = width * height

(三)函数命名

函数命名规范

规范 说明 示例
动词开头 表示动作 calculate_total
小写下划线 使用小写和下划线 get_user_info
表达意图 表达函数功能 validate_email

函数命名示例

python 复制代码
# 好的函数命名
def calculate_total_price(items):
    """计算总价"""
    return sum(item.price for item in items)

def get_user_by_id(user_id):
    """根据ID获取用户"""
    pass

def validate_email(email):
    """验证邮箱格式"""
    pass

def send_notification(user, message):
    """发送通知"""
    pass

# 不好的函数命名
def calc(items):           # 缩写不清晰
    pass

def get(id):               # 含义不明
    pass

def check(email):          # 意图不清
    pass

def send(u, m):            # 参数名不清晰
    pass

# 函数命名最佳实践
# 1. 使用动词+名词结构
def create_user(name, email):
    pass

def update_user(user_id, data):
    pass

def delete_user(user_id):
    pass

def find_user_by_email(email):
    pass

# 2. 返回布尔值的函数用is/has/can开头
def is_valid_email(email):
    pass

def has_permission(user, action):
    pass

def can_access(resource, user):
    pass

# 3. 回调函数用on/when开头
def on_button_click():
    pass

def when_data_loaded():
    pass

(四)类命名

类命名规范

规范 说明 示例
大驼峰 每个单词首字母大写 UserService
名词 使用名词命名 BookManager
表达职责 表达类的职责 OrderProcessor

类命名示例

python 复制代码
# 好的类命名
class UserService:
    """用户服务类"""
    pass

class BookManager:
    """图书管理类"""
    pass

class OrderProcessor:
    """订单处理类"""
    pass

class HttpClient:
    """HTTP客户端类"""
    pass

# 不好的类命名
class service:              # 小写开头
    pass

class mgr:                  # 缩写
    pass

class doSomething:          # 动词开头
    pass

# 类命名最佳实践
# 1. 使用名词命名
class User:
    pass

class Product:
    pass

class Order:
    pass

# 2. 服务类用Service结尾
class UserService:
    pass

class ProductService:
    pass

class OrderService:
    pass

# 3. 管理器类用Manager结尾
class UserManager:
    pass

class CacheManager:
    pass

# 4. 处理器类用Processor/Handler结尾
class DataProcessor:
    pass

class RequestHandler:
    pass

# 5. 抽象类用Abstract/Base前缀
class AbstractUser:
    pass

class BaseRepository:
    pass

🌐 三、代码格式

(一)缩进规范

缩进规范

规范 说明
统一缩进 使用统一的缩进方式
4个空格 Python推荐4个空格
避免Tab 不使用Tab字符

缩进示例

python 复制代码
# 好的缩进(4个空格)
def calculate_total(items):
    total = 0
    for item in items:
        if item.is_valid():
            total += item.price
    return total

# 不好的缩进(混用Tab和空格)
def calculate_total(items):
	total = 0  # Tab
    for item in items:  # 空格
        if item.is_valid():
        	total += item.price  # Tab
    return total

# 缩进最佳实践
# 1. 使用4个空格
class UserService:
    def __init__(self):
        self.users = []
    
    def add_user(self, user):
        if user.is_valid():
            self.users.append(user)
            return True
        return False

# 2. 长行续行使用反斜杠或括号
# 反斜杠续行
total = price + tax + \
        shipping + \
        handling

# 括号续行(推荐)
total = (price + tax +
         shipping +
         handling)

# 3. 列表、字典、元组的格式化
# 短列表
numbers = [1, 2, 3, 4, 5]

# 长列表
numbers = [
    1, 2, 3, 4, 5,
    6, 7, 8, 9, 10,
    11, 12, 13, 14, 15
]

# 字典格式化
user = {
    "name": "Alice",
    "age": 25,
    "email": "alice@example.com"
}

(二)空格规范

空格规范

规范 说明
运算符两侧 运算符两侧加空格
逗号后面 逗号后面加空格
括号内部 括号内部不加空格

空格示例

python 复制代码
# 好的空格
x = 1 + 2              # 运算符两侧有空格
y = [1, 2, 3]          # 逗号后面有空格
result = func(a, b, c) # 括号内部无空格

# 不好的空格
x=1+2                  # 运算符两侧无空格
y=[1,2,3]              # 逗号后面无空格
result = func( a, b, c )  # 括号内部有空格

# 空格最佳实践
# 1. 二元运算符两侧加空格
x = 1 + 2
y = a * b + c / d
z = (a + b) * (c - d)

# 2. 逗号、冒号、分号后面加空格
numbers = [1, 2, 3, 4, 5]
user = {"name": "Alice", "age": 25}
for i in range(10): pass

# 3. 括号内部不加空格
result = func(a, b, c)
numbers = [1, 2, 3]
user = {"name": "Alice"}

# 4. 函数定义的参数列表
def calculate(x, y, z):
    return x + y + z

# 5. 函数调用的参数列表
result = calculate(1, 2, 3)

# 6. 切片操作
numbers = [1, 2, 3, 4, 5]
first_three = numbers[0:3]      # 冒号两侧不加空格
last_two = numbers[-2:]         # 冒号一侧为空时不加空格

(三)空行规范

空行规范

规范 说明
函数之间 函数之间空两行
类之间 类之间空两行
逻辑分组 逻辑分组之间空一行

空行示例

python 复制代码
# 好的空行
import os
import sys


def function_one():
    pass


def function_two():
    pass


class ClassOne:
    pass


class ClassTwo:
    pass


# 不好的空行
import os
import sys
def function_one():
    pass
def function_two():
    pass
class ClassOne:
    pass
class ClassTwo:
    pass

# 空行最佳实践
# 1. 顶层函数和类之间空两行
def function_one():
    pass


def function_two():
    pass


class MyClass:
    pass


# 2. 类方法之间空一行
class UserService:
    def __init__(self):
        self.users = []
    
    def add_user(self, user):
        self.users.append(user)
    
    def get_user(self, user_id):
        for user in self.users:
            if user.id == user_id:
                return user
        return None

# 3. 逻辑分组之间空一行
def process_data(data):
    # 数据验证
    if not data:
        return None
    
    # 数据处理
    result = []
    for item in data:
        processed = transform(item)
        result.append(processed)
    
    # 结果返回
    return result

(四)行长度规范

行长度规范

规范 说明
最大长度 每行不超过79个字符
续行处理 长行使用续行

行长度示例

python 复制代码
# 好的行长度(不超过79字符)
def calculate_total_price(items, tax_rate, discount_rate):
    subtotal = sum(item.price * item.quantity for item in items)
    tax = subtotal * tax_rate
    discount = subtotal * discount_rate
    return subtotal + tax - discount

# 不好的行长度(超过79字符)
def calculate_total_price(items, tax_rate, discount_rate, shipping_rate, handling_rate, gift_wrap_rate):
    subtotal = sum(item.price * item.quantity for item in items) + sum(item.shipping for item in items) + sum(item.handling for item in items)
    tax = subtotal * tax_rate
    discount = subtotal * discount_rate
    return subtotal + tax - discount + shipping_rate + handling_rate + gift_wrap_rate

# 行长度最佳实践
# 1. 使用括号续行
result = some_function(argument1, argument2,
                       argument3, argument4)

# 2. 使用反斜杠续行
total = price + tax + \
        shipping + handling

# 3. 拆分长表达式
# 不好
result = some_dict['key1']['key2']['key3']['key4']['key5']

# 好
level1 = some_dict['key1']
level2 = level1['key2']
level3 = level2['key3']
result = level3['key4']['key5']

# 4. 拆分长字符串
message = (
    "This is a very long message that needs to be "
    "split across multiple lines to maintain "
    "readability and follow the line length limit."
)

💡 四、注释规范

(一)注释原则

注释原则

原则 说明
解释为什么 解释原因而非代码
保持更新 代码修改时更新注释
简洁明了 注释简洁清晰
避免冗余 不注释显而易见的代码

(二)文档注释

文档注释用于描述模块、类、函数的功能。

文档注释示例

python 复制代码
# 模块文档注释
"""
用户管理模块

提供用户注册、登录、信息查询等功能。

作者:张三
日期:2024-01-01
版本:1.0
"""

# 类文档注释
class UserService:
    """
    用户服务类
    
    提供用户管理相关的业务逻辑。
    
    属性:
        users: 用户列表
    
    示例:
        >>> service = UserService()
        >>> service.add_user("Alice")
    """
    
    def __init__(self):
        """初始化用户服务"""
        self.users = []
    
    def add_user(self, username):
        """
        添加用户
        
        参数:
            username: 用户名
        
        返回:
            bool: 添加成功返回True,否则返回False
        
        异常:
            ValueError: 用户名为空时抛出
        
        示例:
            >>> service.add_user("Alice")
            True
        """
        if not username:
            raise ValueError("用户名不能为空")
        self.users.append(username)
        return True

# 函数文档注释
def calculate_total_price(items, tax_rate=0.1):
    """
    计算商品总价
    
    根据商品列表和税率计算总价。
    
    参数:
        items: 商品列表,每个商品包含price和quantity属性
        tax_rate: 税率,默认0.1
    
    返回:
        float: 商品总价
    
    示例:
        >>> items = [Item(100, 2), Item(50, 1)]
        >>> calculate_total_price(items)
        275.0
    """
    subtotal = sum(item.price * item.quantity for item in items)
    return subtotal * (1 + tax_rate)

(三)行内注释

行内注释用于解释代码的具体实现。

行内注释示例

python 复制代码
# 好的行内注释
# 计算用户年龄(当前年份减去出生年份)
age = current_year - birth_year

# 检查用户是否有权限(需要管理员角色)
has_permission = user.role == "admin"

# 使用二分查找提高效率(时间复杂度O(log n))
index = binary_search(sorted_list, target)

# 不好的行内注释
# 将x加1
x = x + 1

# 循环10次
for i in range(10):
    pass

# 如果flag为True
if flag:
    pass

# 行内注释最佳实践
# 1. 解释复杂的算法
# 使用快速排序算法,平均时间复杂度O(n log n)
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

# 2. 解释业务规则
# 根据业务规则,VIP用户享受8折优惠
if user.is_vip:
    price *= 0.8

# 3. 解释特殊处理
# 处理空列表的边界情况
if not items:
    return 0

# 4. 标记待办事项
# TODO: 添加输入验证
# FIXME: 修复内存泄漏问题
# HACK: 临时解决方案,需要重构
# NOTE: 注意这里的性能问题

(四)注释规范总结

注释规范

python 复制代码
# 1. 模块级注释
"""
模块名称:用户管理模块
模块描述:提供用户相关的业务逻辑
作者:张三
创建日期:2024-01-01
版本:1.0
"""

# 2. 类级注释
class UserService:
    """
    用户服务类
    
    描述:提供用户管理功能
    属性:
        users: 用户列表
    """

# 3. 方法级注释
    def add_user(self, username):
        """
        添加用户
        
        参数:
            username (str): 用户名
        返回:
            bool: 成功返回True
        异常:
            ValueError: 用户名为空
        """

# 4. 行内注释
# 解释为什么
x = x + 1  # 补偿偏移量

# 解释复杂的逻辑
# 使用位运算提高效率
if (flags & 0x01) == 0x01:
    pass

# 标记特殊处理
# WARNING: 这里可能有竞态条件

📊 五、良好的编程习惯

(一)代码简洁

代码简洁原则

原则 说明
避免重复 不要重复代码
简化逻辑 简化复杂逻辑
减少嵌套 减少嵌套层次

代码简洁示例

python 复制代码
# 避免重复
# 不好
def process_user(user):
    if user.is_valid():
        if user.has_permission():
            # 处理逻辑1
            pass
    if user.is_valid():
        if user.has_permission():
            # 处理逻辑2
            pass

# 好
def process_user(user):
    if not user.is_valid() or not user.has_permission():
        return
    
    # 处理逻辑1
    # 处理逻辑2

# 简化逻辑
# 不好
def is_eligible(user):
    if user.age >= 18:
        if user.has_account:
            if user.is_active:
                return True
    return False

# 好
def is_eligible(user):
    return (user.age >= 18 and 
            user.has_account and 
            user.is_active)

# 减少嵌套
# 不好
def process_data(data):
    if data:
        for item in data:
            if item.is_valid():
                if item.should_process():
                    process(item)

# 好(使用早返回)
def process_data(data):
    if not data:
        return
    
    for item in data:
        if not item.is_valid():
            continue
        if not item.should_process():
            continue
        process(item)

# 使用列表推导式简化
# 不好
squares = []
for x in range(10):
    squares.append(x * x)

# 好
squares = [x * x for x in range(10)]

# 使用生成器表达式
# 不好
total = 0
for x in range(1000000):
    total += x * x

# 好
total = sum(x * x for x in range(1000000))

(二)代码清晰

代码清晰原则

原则 说明
意图清晰 代码意图明确
逻辑清晰 逻辑结构清晰
命名清晰 命名表达含义

代码清晰示例

python 复制代码
# 意图清晰
# 不好
def f(x):
    return x * 1.1

# 好
def calculate_price_with_tax(price):
    tax_rate = 0.1
    return price * (1 + tax_rate)

# 逻辑清晰
# 不好
def process(order):
    if order:
        if order.items:
            for item in order.items:
                if item.price > 0:
                    # 处理

# 好
def process(order):
    if not order or not order.items:
        return
    
    for item in order.items:
        if item.price <= 0:
            continue
        # 处理

# 使用有意义的变量名
# 不好
d = calculate(a, b)
if d > 100:
    f(d)

# 好
discount = calculate_discount(original_price, quantity)
if discount > MAX_DISCOUNT:
    apply_discount(discount)

# 使用常量代替魔法数字
# 不好
if user.age >= 18:
    pass
if len(password) >= 8:
    pass

# 好
MIN_AGE = 18
MIN_PASSWORD_LENGTH = 8

if user.age >= MIN_AGE:
    pass
if len(password) >= MIN_PASSWORD_LENGTH:
    pass

(三)代码一致

代码一致原则

原则 说明
命名一致 命名风格统一
格式一致 代码格式统一
风格一致 编码风格统一

代码一致示例

python 复制代码
# 命名一致
# 不好
user_name = "Alice"
userAge = 25        # 驼峰命名
user_email = "alice@example.com"  # 下划线命名
UserPhone = "123"   # 大驼峰命名

# 好(统一使用下划线命名)
user_name = "Alice"
user_age = 25
user_email = "alice@example.com"
user_phone = "123"

# 格式一致
# 不好
def func1(a,b,c):    # 逗号后无空格
    return a+b+c     # 运算符无空格

def func2(a, b, c):  # 逗号后有空格
    return a + b + c # 运算符有空格

# 好(统一格式)
def func1(a, b, c):
    return a + b + c

def func2(x, y, z):
    return x + y + z

# 风格一致
# 不好
def get_user(id):
    return db.query(id)

def GetUser(id):      # 命名风格不一致
    return db.query(id)

def fetch_user(id):   # 动词不一致
    return db.query(id)

# 好(统一风格)
def get_user(user_id):
    return db.query(user_id)

def get_product(product_id):
    return db.query(product_id)

def get_order(order_id):
    return db.query(order_id)

📝 六、代码重构

(一)重构原则

重构原则

原则 说明
小步前进 每次小改动
测试保护 有测试保障
保持功能 不改变功能

(二)重构方法

重构方法

python 复制代码
# 1. 提取函数
# 重构前
def process_order(order):
    # 验证订单
    if not order:
        return False
    if not order.items:
        return False
    
    # 计算总价
    total = 0
    for item in order.items:
        total += item.price * item.quantity
    
    # 应用折扣
    if total > 1000:
        total *= 0.9
    
    # 保存订单
    db.save(order)
    
    return True

# 重构后
def process_order(order):
    if not validate_order(order):
        return False
    
    total = calculate_total(order)
    total = apply_discount(total)
    
    save_order(order)
    return True

def validate_order(order):
    if not order or not order.items:
        return False
    return True

def calculate_total(order):
    return sum(item.price * item.quantity for item in order.items)

def apply_discount(total):
    if total > 1000:
        return total * 0.9
    return total

def save_order(order):
    db.save(order)

# 2. 合并重复代码
# 重构前
def process_user(user):
    if user.is_valid():
        log.info(f"Processing user {user.name}")
        # 处理逻辑
        log.info(f"User {user.name} processed")

def process_admin(admin):
    if admin.is_valid():
        log.info(f"Processing admin {admin.name}")
        # 处理逻辑
        log.info(f"Admin {admin.name} processed")

# 重构后
def process_person(person, person_type):
    if not person.is_valid():
        return
    
    log.info(f"Processing {person_type} {person.name}")
    # 处理逻辑
    log.info(f"{person_type} {person.name} processed")

def process_user(user):
    process_person(user, "User")

def process_admin(admin):
    process_person(admin, "Admin")

# 3. 简化条件表达式
# 重构前
def is_eligible_for_discount(user):
    if user.age >= 60:
        return True
    if user.is_student:
        return True
    if user.is_veteran:
        return True
    return False

# 重构后
def is_eligible_for_discount(user):
    eligible_conditions = [
        user.age >= 60,
        user.is_student,
        user.is_veteran
    ]
    return any(eligible_conditions)

# 4. 使用多态取代条件
# 重构前
def calculate_shipping_cost(order):
    if order.shipping_method == "standard":
        return 5.0
    elif order.shipping_method == "express":
        return 10.0
    elif order.shipping_method == "overnight":
        return 20.0
    return 0.0

# 重构后
class ShippingMethod:
    def calculate_cost(self):
        pass

class StandardShipping(ShippingMethod):
    def calculate_cost(self):
        return 5.0

class ExpressShipping(ShippingMethod):
    def calculate_cost(self):
        return 10.0

class OvernightShipping(ShippingMethod):
    def calculate_cost(self):
        return 20.0

def calculate_shipping_cost(order):
    return order.shipping_method.calculate_cost()

📝 总结

程序设计风格是程序员的基本素养。

🎯 程序设计风格概述

  • 定义:编写代码时遵循的规范和习惯
  • 重要性:提高可读性、可维护性、协作效率
  • 原则:清晰性、简洁性、一致性、可读性、可维护性

💡 命名规范

  • 变量命名:见名知意、小写下划线
  • 函数命名:动词开头、表达意图
  • 类命名:大驼峰、名词命名

📦 代码格式

  • 缩进规范:4个空格、统一缩进
  • 空格规范:运算符两侧、逗号后面
  • 空行规范:函数之间、逻辑分组
  • 行长度:不超过79字符

🌐 注释规范

  • 文档注释:模块、类、函数
  • 行内注释:解释为什么、保持更新
  • 注释原则:简洁明了、避免冗余

📊 良好习惯

  • 代码简洁:避免重复、简化逻辑
  • 代码清晰:意图清晰、逻辑清晰
  • 代码一致:命名一致、格式一致

📝 代码重构

  • 重构原则:小步前进、测试保护
  • 重构方法:提取函数、合并重复、简化条件

核心启示:良好的程序设计风格是高质量代码的基础。它不仅能提高代码的可读性和可维护性,还能减少错误、提高开发效率。在实际工作中,我们需要注意:第一,遵循命名规范,使代码见名知意;第二,保持代码格式统一,提高可读性;第三,编写有意义的注释,解释代码意图;第四,保持代码简洁清晰,避免复杂逻辑;第五,持续重构,保持代码质量。记住:代码是写给人看的,只是恰好能被机器执行。


相关推荐
xierui12312314 小时前
OpenAI 拟停止向 Cursor供模:如何设计不绑供应商的AIAgent架构
人工智能·系统架构·软件工程
智造ERP规划20 小时前
装备制造 ERP↔WMS 集成深度拆解:大型物料、项目专属库与齐套管理的 6 个核心场景
系统架构·软件工程·制造
郝学胜-神的一滴1 天前
Effective Python 条款4:字符串格式化大乱斗
开发语言·网络·python·程序人生·软件工程
xierui1231232 天前
长时间运行的AI Agent 如何安全停机:预算、熔断、人工接管与状态回读
人工智能·软件工程
老郑聊AI业财智造2 天前
从“思考-行动”到“知行合一”:ReActAgent的架构原理与工程实践全景剖析
人工智能·架构·系统架构·软件工程·软件构建
梁辰兴3 天前
软件工程:程序设计语言的分类
软件工程·梁辰兴·按发展历史分类·程序设计语言的分类·按编程范式分类·按执行方式分类·按应用领域分类
老郑聊AI业财智造3 天前
数据不搬家,也能做检索:Milvus的“湖原生”架构革命
人工智能·ai·架构·软件工程·软件构建·milvus
梁辰兴3 天前
软件工程:系统设计
软件工程·设计原则·系统设计·设计工具·设计方法·梁辰兴·设计阶段
深念Y4 天前
约束工程:如何让 AI 没法跑偏
人工智能·ai·软件工程·codex·opencode·ccsiwtch