修复糟糕的代码气味

简介: 修复糟糕的代码气味

原文链接:https://www.arjancodes.com/blog/best-practices-for-eliminating-python-code-smells/

文章列举了多种糟糕的代码模式,并给出了解决方法。通过这些修改,可以使得代码更易读、更可维护。

这些糟糕的代码气味是:

  1. 万能对象:一个类具有太多的功能,违背了单一责任原则。这个类会变得复杂,难以测试和维护。 解决方法:根据任务拆分成多个类。
  2. 重复代码:相同的代码块多次出现,增加了冗余,并且增加维护难度。 解决方法:抽象出一个函数,通过调用函数替代多个相同的代码块。
  3. 过长的方法:一个方法太长,说明这个方法做了太多事情,理解和维护该方法会很困难。 解决方法: 按照功能,拆分成若干的方法。
  4. 神奇数字: 代码中出现的神秘数字难以理解和修改。解决方法:定义一个常量表示数字的含义。
  5. 嵌套过深:过多的嵌套使得函数的流程难以把握。 解决办法: 去掉嵌套条件,必要时创建函数。

1. The “god object” smell (万能对象)

class OnlineStore:
    def search_product(self, query: Query):
        # Logic to search for products in some database
        pass
    def process_order(self, order: Order):
        # Logic to process the order and send confirmation email
        pass
    def handle_payment(self, payment_info: PaymentInfo):
        # Logic to handle payment and update the order status
        pass
    def manage_inventory(self, product_id: int, quantity: int):
        # Logic to manage inventory and update the database
        pass
    # Many more methods

“上帝对象”是整体设计的,处理了太多的任务和责任,违反了SOLID设计的单一责任原则(SRP, Single Responsibility priciple)。代码示例中的 OnlineStore类负责库存管理、订单处理、付款接受和产品搜索。将所有这些职责合并到一个类别中可能会限制我们引入新功能的灵活性,同时增加测试和维护的复杂性。

我们可以将 OnlineStore 类重写为更易于管理的专用类(如 ProductSearch 、 OrderProcessor 、 PaymentGateway 和 InventoryManager )。这使得每个类在遵守 SRP 的同时专注于特定任务。

class ProductSearch:
    def search_product(self, query: Query):
        # Logic to search for products in some database
        pass

class OrderProcessor:
    def process_order(self, order: Order):
        # Logic to process the order and send confirmation email
        pass

class PaymentGateway:
    def handle_payment(self, total: int, payment_info: Payment):
        # Logic to handle payment and update the order status
        pass

class InventoryManager:
    def manage_inventory(self, product_id: int, quantity: int):
        # Logic to manage inventory and update the database
        pass

2. The “duplicate code” smell (重复代码)

class ReportGenerator:
    def generate_sales_report(self, sales_data: list[Report):
        # Preprocessing steps, such as formatting the data into a table.
        # Generate sales report
        pass

    def generate_inventory_report(self, inventory_data: list[Report]):
        # Preprocessing steps (duplicated)
        # Generate inventory report
        pass

当相同的代码块多次出现时,它被视为重复代码。重复代码增加了冗余和不一致的可能。

我们可以将这些重复的过程组合成一个单一的方法来解决这个问题。通过这种方式,我们消除了冗余,并将其与 DRY(不要重复自己)编码理念保持一致。

class ReportGenerator:
    def preprocess_data(self, data: list[Report]):
        # Common preprocessing steps
        pass

    def generate_sales_report(self, sales_data: list[Report]):
        self.preprocess_data(sales_data)
        # Generate sales report
        pass

    def generate_inventory_report(self, inventory_data: list[Report]):
        self.preprocess_data(inventory_data)
        # Generate inventory report
        pass


3. The “long method” smell (方法太长)

def handle_customer_request(request: CustomerRequest):
    # Validate request
    # Log request details
    # Check inventory
    # Calculate pricing
    # Apply discounts
    # Finalize response
    pass

“长方法”包含太多的代码行,并且通常难以阅读、理解和测试。

通过将此方法分解为更小、更集中的函数,可以提高可读性和可重用性。通过将方法分离成更小、更集中的函数,我们可以提高可读性和可重用性,并简化单元测试。我们应该致力于使每种方法都负责一项单一的任务。

def handle_customer_request(request: CustomerRequest):
    validate_request(request)
    log_request(request)
    check_inventory(request)
    pricing = calculate_pricing(request)
    apply_discounts(pricing)
    return finalize_response(pricing)

def validate_request(request: Request): pass
def log_request(request: Request): pass
def check_inventory(request: Request): pass
def calculate_pricing(request: Request): pass
def apply_discounts(pricing: int): pass
def finalize_response(pricing: int): pass

4. The “magic numbers” smell (神奇数字)

def calculate_shipping_cost(distance: float) -> float:
    return distance * 1.25  # What does 1.25 signify?

“幻数”是那些棘手的数字文字,经常出现在编程代码中,没有明显的解释,使代码更难理解和处理。该 calculate_shipping_cost 函数在没有任何上下文的情况下使用数字 1.25,让我们猜测它的目的和含义。

相反,我们可以引入一个名为 PER_MILE_SHIPPING_RATE 的常量,它清楚地表明 1.25 表示每英里的运输成本。这个简单的更改使我们的代码更易于理解,也简化了将来对此值的更改。

PER_MILE_SHIPPING_RATE = 1.25

def calculate_shipping_cost(distance: float) -> float:
    return distance * PER_MILE_SHIPPING_RATE

5. The “nested conditionals” smell(嵌套过深)

def approve_loan(application: LoanApplication) -> bool:
    if application.credit_score > 600:
        if application.income > 30000:
            if application.debt_to_income_ratio < 0.4:
                return True
            else:
                return False
        else:
            return False
    else:
        return False

嵌套的条件语句可能会使理解函数的流变得困难。该 approve_loan 方法被一系列难以理解的嵌套 if 语句包围。

通过重构我们的代码,以便按顺序检查每个条件,我们可以创建一个更扁平、更易于阅读和理解的结构。如果将复杂的逻辑与条件混合在一起,则可能值得将逻辑抽象为单独的函数,以使条件更易于阅读。如果您有一系列需要满足的条件,请考虑使用 any 和 all 内置函数来使条件更具可读性。

def approve_loan(application: LoanApplication) -> bool:
    if application.credit_score <= 600:
        return False
    if application.income <= 30000:
        return False
    if application.debt_to_income_ratio >= 0.4:
        return False
    return True
def approve_loan(application: LoanApplication) -> bool:
    return all([
        application.credit_score > 600,
        application.income > 30000,
        application.debt_to_income_ratio < 0.4
    ])
相关文章
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8045 0
|
10天前
|
域名解析 人工智能 Linux
|
20天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
17945 63
|
18天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
4天前
|
人工智能 安全 网络安全
|
1天前
|
人工智能 弹性计算 安全
阿里云 码上2027 AI coding 嘉年华
阿里云“码上2027”AI Coding嘉年华于2026年12月2—3日在上海西岸艺术中心举行,聚焦AI Coding从单点提效迈向企业级研发体系升级。发布Qwen4-max模型、QBot智能协作、AgentCore平台等重磅成果,并推出ECS云服务器特惠(200Mbps流量月付40元起)。
753 0
|
7天前
|
云安全 数据采集 人工智能
|
9天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1445 5
|
15天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2539 8
|
20天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
4041 22