本文旨在探讨如何通过应用SOLID原则、整洁代码实践和设计模式,对一个复杂的PHP函数进行重构。我们将重点关注如何优化多条件判断和数据验证逻辑,通过引入卫语句、数据映射和职责分离,显著提升代码的可读性、可维护性和健壮性,同时避免直接照搬原文,以专业教程风格呈现。
在软件开发中,随着项目功能的迭代,代码库往往会变得复杂且难以维护。一个常见的挑战是函数内部包含过多的条件判断和业务逻辑,导致代码冗长、可读性差,并违反单一职责原则(srp)。本教程将以一个具体的php函数为例,演示如何通过一系列重构技巧来改善代码质量。
原始函数分析与问题识别
考虑以下原始execute方法,它负责处理饮料订单的逻辑:
protected function execute(InputInterface $input, OutputInterface $output): int { $this->setDrinkType($input); if (in_array($this->drinkType, $this->allowedDrinkTypes)) { // ... 饮料类型合法,继续处理 ... $money = $input->getArgument('money'); switch ($this->drinkType) { case 'tea': if ($money < 0.4) { $output->writeln('The tea costs 0.4'); return 0; } break; case 'coffee': if ($money < 0.5) { $output->writeln('The coffee costs 0.5'); return 0; } break; case 'chocolate': if ($money < 0.6) { $output->writeln('The chocolate costs 0.6'); return 0; } break; } if ($this->hasCorrectSugars($input)) { $this->checkSugars($input, $output); return 0; } $output->writeln('The number of sugars should be between 0 and 2'); return 0; } $output->writeln('The drink type should be tea, coffee or chocolate'); return 0; } protected function hasCorrectSugars($input): bool { $sugars = $input->getArgument('sugars'); return ($sugars >= $this->minSugars && $sugars <= $this->maxSugars); } protected function checkSugars($input, $output): void { $sugars = $input->getArgument('sugars'); $output->write('You have ordered a ' . $this->drinkType); $this->isExtraHot($input, $output); // 假设存在此方法 $output->write(' with ' . $sugars . ' sugars'); if ($sugars > 0) { $output->write(' (stick included)'); } $output->writeln(''); }
该函数存在以下几个主要问题:
- 嵌套深度过大: if语句和switch语句的层层嵌套使得代码难以阅读和理解。
- 职责不单一: execute方法承担了多种职责,包括验证饮料类型、检查金额、验证糖量以及输出信息。这违反了单一职责原则。
- 重复逻辑: switch语句中对不同饮料类型的金额检查逻辑相似,存在重复。
- 魔术数字: 饮料成本(0.4, 0.5, 0.6)直接硬编码在代码中。
- 返回逻辑不清晰: 无论成功或失败,函数都返回0,这不符合通常的Unix/命令行程序惯例(0表示成功,非0表示失败)。
- hasCorrectSugars与checkSugars的混淆: 尽管hasCorrectSugars用于验证,但checkSugars似乎更侧重于输出订单详情,职责边界不够清晰。
重构策略与步骤
我们将采用以下策略来重构此函数:
- 卫语句(Guard Clauses): 使用反向条件和提前返回来扁平化嵌套结构。
- 数据映射: 将硬编码的成本数据抽取到数据结构中,消除switch语句。
- 职责分离: 确保每个函数只做一件事。
- 清晰的错误处理: 通过返回不同的状态码或抛出异常来明确指示操作结果。
步骤一:使用卫语句处理非法饮料类型
首先,我们将外层if语句反转,以便在饮料类型不合法时立即返回,避免后续逻辑的嵌套。
protected function execute(InputInterface $input, OutputInterface $output): int { $this->setDrinkType($input); // 卫语句:处理非法饮料类型 if (!in_array($this->drinkType, $this->allowedDrinkTypes)) { $output->writeln('The drink type should be tea, coffee or chocolate'); return 1; // 返回非0表示失败 } // 后续逻辑将在此处开始,不再嵌套 // ... }
通过这种方式,主流程的逻辑不再被包裹在一个大的if块中,提高了可读性。
步骤二:替换switch语句为数据映射
为了消除重复的金额检查逻辑和硬编码的成本,我们可以将饮料成本存储在一个关联数组(或映射)中。
protected function execute(InputInterface $input, OutputInterface $output): int { $this->setDrinkType($input); if (!in_array($this->drinkType, $this->allowedDrinkTypes)) { $output->writeln('The drink type should be tea, coffee or chocolate'); return 1; } // 使用数据映射存储饮料成本,可作为类成员变量 $drinkCosts = [ 'tea' => 0.4, 'coffee' => 0.5, 'chocolate' => 0.6 ]; $money = $input->getArgument('money'); $drinkCost = $drinkCosts[$this->drinkType]; // 从映射中获取成本 // 卫语句:检查金额是否足够 if ($money < $drinkCost) { $output->writeln('The ' . $this->drinkType . ' costs ' . $drinkCost); return 1; } // ... 继续处理糖量和订单输出 ... }
这种方式不仅移除了switch语句,使得代码更简洁,而且使得添加新的饮料类型时,只需更新$drinkCosts数组,而无需修改execute方法的逻辑,符合开放封闭原则(OCP)。
步骤三:简化糖量验证和输出逻辑
糖量验证逻辑已经封装在hasCorrectSugars中,我们可以直接利用它,并同样采用卫语句。checkSugars则专注于输出订单详情。
protected function execute(InputInterface $input, OutputInterface $output): int { $this->setDrinkType($input); if (!in_array($this->drinkType, $this->allowedDrinkTypes)) { $output->writeln('The drink type should be tea, coffee or chocolate'); return 1; } $drinkCosts = [ 'tea' => 0.4, 'coffee' => 0.5, 'chocolate' => 0.6 ]; $money = $input->getArgument('money'); $drinkCost = $drinkCosts[$this->drinkType]; if ($money < $drinkCost) { $output->writeln('The ' . $this->drinkType . ' costs ' . $drinkCost); return 1; } // 卫语句:检查糖量是否正确 if (!$this->hasCorrectSugars($input)) { $output->writeln('The number of sugars should be between 0 and 2'); return 1; } // 所有验证通过,执行订单输出逻辑 $this->checkSugars($input, $output); return 0; // 成功返回0 } // hasCorrectSugars 保持不变,它只负责验证 protected function hasCorrectSugars($input): bool { $sugars = $input->getArgument('sugars'); return ($sugars >= $this->minSugars && $sugars <= $this->maxSugars); } // checkSugars 保持不变,它只负责输出 protected function checkSugars($input, $output): void { $sugars = $input->getArgument('sugars'); $output->write('You have ordered a ' . $this->drinkType); $this->isExtraHot($input, $output); $output->write(' with ' . $sugars . ' sugars'); if ($sugars > 0) { $output->write(' (stick included)'); } $output->writeln(''); }
重构后的代码与优势
经过上述重构,execute方法变得更加清晰和简洁。
<?php use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class OrderProcessor { protected string $drinkType; protected array $allowedDrinkTypes = ['tea', 'coffee', 'chocolate']; protected float $minSugars = 0; protected float $maxSugars = 2; // 建议将此映射作为类属性或通过构造函数注入 protected array $drinkCosts = [ 'tea' => 0.4, 'coffee' => 0.5, 'chocolate' => 0.6 ]; protected function setDrinkType(InputInterface $input): void { // 假设此处从输入中获取并设置 $this->drinkType $this->drinkType = $input->getArgument('drinkType'); } // 假设存在此方法,用于处理是否额外加热 protected function isExtraHot(InputInterface $input, OutputInterface $output): void { // 示例逻辑 if ($input->getOption('extraHot')) { $output->write(' (extra hot)'); } } /** * 执行饮料订单处理逻辑。 * * @param InputInterface $input * @param OutputInterface $output * @return int 0 表示成功,非0表示失败。 */ protected function execute(InputInterface $input, OutputInterface $output): int { $this->setDrinkType($input); // 1. 验证饮料类型 if (!in_array($this->drinkType, $this->allowedDrinkTypes)) { $output->writeln('The drink type should be tea, coffee or chocolate'); return 1; } // 2. 验证金额是否足够 $money = $input->getArgument('money'); $drinkCost = $this->drinkCosts[$this->drinkType] ?? null; // 使用 null 合并操作符处理不存在的键 if ($drinkCost === null) { // 理论上不会发生,因为 drinkType 已经通过 allowedDrinkTypes 验证 $output->writeln('Invalid drink type configuration.'); return 1; } if ($money < $drinkCost) { $output->writeln('The ' . $this->drinkType . ' costs ' . $drinkCost); return 1; } // 3. 验证糖量 if (!$this->hasCorrectSugars($input)) { $output->writeln('The number of sugars should be between ' . $this->minSugars . ' and ' . $this->maxSugars); return 1; } // 4. 所有验证通过,输出订单详情 $this->checkSugars($input, $output); return 0; // 成功 } /** * 检查糖量是否在允许范围内。 * * @param InputInterface $input * @return bool */ protected function hasCorrectSugars(InputInterface $input): bool { $sugars = $input->getArgument('sugars'); // 确保 $sugars 是数值类型,避免潜在的类型比较问题 return is_numeric($sugars) && ($sugars >= $this->minSugars && $sugars <= $this->maxSugars); } /** * 输出订单的糖量信息。 * * @param InputInterface $input * @param OutputInterface $output * @return void */ protected function checkSugars(InputInterface $input, OutputInterface $output): void { $sugars = $input->getArgument('sugars'); $output->write('You have ordered a ' . $this->drinkType); $this->isExtraHot($input, $output); $output->write(' with ' . $sugars . ' sugars'); if ($sugars > 0) { $output->write(' (stick included)'); } $output->writeln(''); } }
重构后的优势:
- 更高的可读性: 通过卫语句,代码的流程变得线性,易于理解。每个条件判断都处理一个特定的失败场景并立即返回。
- 更强的可维护性: 业务逻辑被分解为更小的、职责单一的块。修改或添加新的饮料类型、成本或验证规则变得更容易。
- 更好的可扩展性: drinkCosts映射的使用使得添加新饮料类型无需修改核心逻辑。如果未来饮料的成本计算变得复杂(例如,根据会员等级),可以进一步抽象为策略模式。
-
符合SOLID原则:
- 单一职责原则 (SRP): execute方法主要负责协调验证和输出,而具体的验证逻辑(如hasCorrectSugars)和输出逻辑(如checkSugars)则由各自的函数负责。
- 开放封闭原则 (OCP): 添加新的饮料类型,无需修改execute方法,只需更新$drinkCosts数组。
- 清晰的错误处理: 通过返回0表示成功,非0表示失败,与命令行程序的标准实践保持一致。
注意事项与进一步优化
- 依赖注入: InputInterface和OutputInterface可以直接通过构造函数注入,而不是作为方法参数传递,这有助于提高类的可测试性。
- 错误码: 可以定义更具体的错误码,例如1表示无效饮料类型,2表示金额不足,3表示糖量错误,以便调用方更精确地判断失败原因。
- 领域模型: 对于更复杂的业务场景,可以考虑引入领域模型(如Drink、Order对象),将相关的属性和行为封装起来,进一步提高代码的内聚性。例如,Drink对象可以拥有自己的cost方法。
- 异常处理: 在某些情况下,抛出特定异常(如InvalidArgumentException、InsufficientMoneyException)可能比返回错误码更符合面向对象的设计,尤其是在非命令行应用中。
- 配置管理: allowedDrinkTypes、minSugars、maxSugars和drinkCosts这些常量或配置数据,可以从外部配置文件或服务中加载,而不是硬编码在类中。
总结
通过本教程,我们演示了如何将一个包含多层嵌套和复杂逻辑的函数,通过应用卫语句、数据映射和职责分离等重构技术,转化为一个更具可读性、可维护性和扩展性的代码。重构不仅仅是改变代码的外观,更是提升代码内在质量、使其更易于理解和适应未来变化的关键实践。在日常开发中,持续关注代码质量,并适时进行重构,是构建健壮、可伸缩软件系统的重要组成部分。
暂无评论内容