萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 函數設計原則:高內聚低耦合、單一職責、參數返回值規範

函數設計三大核心維度

  1. 聚合性:函數內部元素關聯程度 — 高內聚 (單一職責)
  2. 耦合性:函數間依賴程度 — 低耦合 (參數/返回值通信)
  3. 規模:函數代碼行數、嵌套深度 — 小而精

原則一:單一職責 (高內聚)

每個函數只做一件事,並把這件事做好。

反模式:大雜燴函數


def process_order(user_id, items, payment_info, shipping_address, send_email=True):
    # 1. 驗證用戶
    # 2. 計算價格
    # 3. 處理支付
    # 4. 扣減庫存
    # 5. 創建訂單
    # 6. 發送郵件
    # 7. 記錄日誌
    # 8. 返回結果
    pass  # 200+ 行代碼...

正模式:職責拆分


def validate_user(user_id): ...
def calculate_total(items): ...
def process_payment(payment_info, amount): ...
def reserve_inventory(items): ...
def create_order(user_id, items, payment_result): ...
def send_confirmation_email(order): ...
def log_order_event(order, event): ...

def process_order(user_id, items, payment_info, shipping_address):
    validate_user(user_id)
    total = calculate_total(items)
    payment_result = process_payment(payment_info, total)
    reserve_inventory(items)
    order = create_order(user_id, items, payment_result, shipping_address)
    send_confirmation_email(order)
    log_order_event(order, 'created')
    return order

優勢:可測試、可復用、易閱讀、易修改、易組合。

原則二:保持簡單、保持簡短

  • 屏幕法則:函數體應在一屏內可見 (約 50-80 行)
  • 嵌套深度:≤ 3 層 (if/for/while),超過即重構
  • 參數數量:≤ 4 個,超過用對象/數據類封裝
  • 返回值:單一返回類型,避免「或返回 None 或列表或錯誤碼」

Python 優勢:表達力強,代碼天然更短


# C++ 可能 20 行,Python 3 行
def parse_config(lines):
    return {k.strip(): v.strip() 
            for line in lines 
            if '=' in line 
            for k, v in [line.split('=', 1)]}

原則三:輸入用參數、輸出用返回值 (低耦合)

❌ 反模式:全局變量通信


# 全局狀態 — 並發災難、測試噩夢、隱式依賴
CACHE = {}
DB_CONN = None

def get_user(id):
    global DB_CONN
    if id in CACHE: return CACHE[id]
    cursor = DB_CONN.cursor()
    # ...

✅ 正模式:顯式依賴注入


def get_user(user_id, db_conn, cache=None):
    cache = cache or {}
    if user_id in cache:
        return cache[user_id]
    cursor = db_conn.cursor()
    # ...
    return user

✅ 返回值規範


# 成功返回結果,失敗拋異常 (Python 風格)
def divide(a, b):
    if b == 0:
        raise ValueError("Division by zero")
    return a / b

# 多返回值用元組/命名元組/數據類
from collections import namedtuple
Result = namedtuple('Result', 'success data error')

def safe_divide(a, b):
    try:
        return Result(True, a/b, None)
    except ZeroDivisionError as e:
        return Result(False, None, str(e))

原則四:慎用全局變量

性能視角:局部變量更快


import timeit

GLOBAL = 5
def global_access():
    return GLOBAL + 1

def local_access():
    local = 5
    return local + 1

# 測試
print(timeit.timeit(global_access, number=10_000_000))  # ~1.2s
print(timeit.timeit(local_access, number=10_000_000))   # ~0.8s

Python 變量查找順序:Local → Enclosing → Global → Builtin (LEGB),局部最快。

原則五:避免修改可變參數 (副作用控制)


# ❌ 修改調用者傳入的列表
def bad_add_item(items, item):
    items.append(item)  # 副作用!

# ✅ 返回新列表 (函數式風格)
def good_add_item(items, item):
    return items + [item]

# ✅ 或明確文檔並複製
def documented_add_item(items, item):
    """添加項目並返回新列表,不修改原列表"""
    new_items = list(items)  # 淺拷貝
    new_items.append(item)
    return new_items

原則六:避免直接修改其他模塊變量


# a.py
PI = 3.14

# b.py
import a
# ❌ 直接修改
a.PI = 3.14159  # 影響所有導入 a 的模塊!

# ✅ 提供設置函數
# a.py
def set_pi(value):
    global PI
    PI = value

# b.py
import a
a.set_pi(3.14159)  # 明確意圖、可加驗證、可觀測

綜合重構示例


# 重構前:200行單體函數
def generate_report(data, config, output_path):
    # 連接DB、查詢、計算、格式化、寫文件、發郵件、記錄日誌...

# 重構後:管道式組合
def generate_report(data, config, output_path):
    validated = validate_input(data, config)
    enriched = enrich_data(validated, db_conn)
    calculated = calculate_metrics(enriched)
    formatted = format_report(calculated, config.template)
    write_file(formatted, output_path)
    notify_stakeholders(formatted, config.recipients)
    log_completion(output_path)

檢查清單

  • [ ] 函數名動詞開頭,精確描述行為
  • [ ] 單一職責,無副作用或副作用文檔化
  • [ ] 參數 ≤ 4,複雜參數用 dataclass/TypedDict
  • [ ] 返回類型固定,異常用 raise
  • [ ] 無全局狀態依賴,依賴注入
  • [ ] 無修改可變參數 (或明確文檔)
  • [ ] 代碼 ≤ 50 行,嵌套 ≤ 3 層
  • [ ] 有類型提示、文檔字符串、單元測試

遵循這些原則,Python 代碼將具備優秀的可讀性、可測試性、可維護性與可擴展性。

copyright © 萬盛學電腦網 all rights reserved