修复糟糕的代码气味

2024-04-12 16:52
文章标签 代码 修复 糟糕 气味

本文主要是介绍修复糟糕的代码气味,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

修复糟糕的代码气味

在这里插入图片描述

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

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

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

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

class OnlineStore:def search_product(self, query: Query):# Logic to search for products in some databasepassdef process_order(self, order: Order):# Logic to process the order and send confirmation emailpassdef handle_payment(self, payment_info: PaymentInfo):# Logic to handle payment and update the order statuspassdef manage_inventory(self, product_id: int, quantity: int):# Logic to manage inventory and update the databasepass# 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 databasepassclass OrderProcessor:def process_order(self, order: Order):# Logic to process the order and send confirmation emailpassclass PaymentGateway:def handle_payment(self, total: int, payment_info: Payment):# Logic to handle payment and update the order statuspassclass InventoryManager:def manage_inventory(self, product_id: int, quantity: int):# Logic to manage inventory and update the databasepass

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 reportpassdef generate_inventory_report(self, inventory_data: list[Report]):# Preprocessing steps (duplicated)# Generate inventory reportpass

当相同的代码块多次出现时,它被视为重复代码。重复代码增加了冗余和不一致的可能。
我们可以将这些重复的过程组合成一个单一的方法来解决这个问题。通过这种方式,我们消除了冗余,并将其与 DRY(不要重复自己)编码理念保持一致。

class ReportGenerator:def preprocess_data(self, data: list[Report]):# Common preprocessing stepspassdef generate_sales_report(self, sales_data: list[Report]):self.preprocess_data(sales_data)# Generate sales reportpassdef generate_inventory_report(self, inventory_data: list[Report]):self.preprocess_data(inventory_data)# Generate inventory reportpass

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

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

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

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

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.25def 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 Trueelse:return Falseelse:return Falseelse:return False

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

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

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

或者使用 any/all 内置函数:

def approve_loan(application: LoanApplication) -> bool:return all([application.credit_score > 600,application.income > 30000,application.debt_to_income_ratio < 0.4])

这篇关于修复糟糕的代码气味的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/897700

相关文章

qt5cored.dll报错怎么解决? 电脑qt5cored.dll文件丢失修复技巧

《qt5cored.dll报错怎么解决?电脑qt5cored.dll文件丢失修复技巧》在进行软件安装或运行程序时,有时会遇到由于找不到qt5core.dll,无法继续执行代码,这个问题可能是由于该文... 遇到qt5cored.dll文件错误时,可能会导致基于 Qt 开发的应用程序无法正常运行或启动。这种错

电脑提示xlstat4.dll丢失怎么修复? xlstat4.dll文件丢失处理办法

《电脑提示xlstat4.dll丢失怎么修复?xlstat4.dll文件丢失处理办法》长时间使用电脑,大家多少都会遇到类似dll文件丢失的情况,不过,解决这一问题其实并不复杂,下面我们就来看看xls... 在Windows操作系统中,xlstat4.dll是一个重要的动态链接库文件,通常用于支持各种应用程序

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Java中Map.Entry()含义及方法使用代码

《Java中Map.Entry()含义及方法使用代码》:本文主要介绍Java中Map.Entry()含义及方法使用的相关资料,Map.Entry是Java中Map的静态内部接口,用于表示键值对,其... 目录前言 Map.Entry作用核心方法常见使用场景1. 遍历 Map 的所有键值对2. 直接修改 Ma

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

pandas实现数据concat拼接的示例代码

《pandas实现数据concat拼接的示例代码》pandas.concat用于合并DataFrame或Series,本文主要介绍了pandas实现数据concat拼接的示例代码,具有一定的参考价值,... 目录语法示例:使用pandas.concat合并数据默认的concat:参数axis=0,join=

C#代码实现解析WTGPS和BD数据

《C#代码实现解析WTGPS和BD数据》在现代的导航与定位应用中,准确解析GPS和北斗(BD)等卫星定位数据至关重要,本文将使用C#语言实现解析WTGPS和BD数据,需要的可以了解下... 目录一、代码结构概览1. 核心解析方法2. 位置信息解析3. 经纬度转换方法4. 日期和时间戳解析5. 辅助方法二、L

Python使用Code2flow将代码转化为流程图的操作教程

《Python使用Code2flow将代码转化为流程图的操作教程》Code2flow是一款开源工具,能够将代码自动转换为流程图,该工具对于代码审查、调试和理解大型代码库非常有用,在这篇博客中,我们将深... 目录引言1nVflRA、为什么选择 Code2flow?2、安装 Code2flow3、基本功能演示

IIS 7.0 及更高版本中的 FTP 状态代码

《IIS7.0及更高版本中的FTP状态代码》本文介绍IIS7.0中的FTP状态代码,方便大家在使用iis中发现ftp的问题... 简介尝试使用 FTP 访问运行 Internet Information Services (IIS) 7.0 或更高版本的服务器上的内容时,IIS 将返回指示响应状态的数字代