
在软件开发中,随着项目功能的迭代,代码库往往会变得复杂且难以维护。一个常见的挑战是函数内部包含过多的条件判断和业务逻辑,导致代码冗长、可读性差,并违反单一职责原则(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语句反转,以便在饮料类型不合法时立即返回,避免后续逻辑的嵌套。
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块中,提高了可读性。
为了消除重复的金额检查逻辑和硬编码的成本,我们可以将饮料成本存储在一个关联数组(或映射)中。
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('');
}
}重构后的优势:
通过本教程,我们演示了如何将一个包含多层嵌套和复杂逻辑的函数,通过应用卫语句、数据映射和职责分离等重构技术,转化为一个更具可读性、可维护性和扩展性的代码。重构不仅仅是改变代码的外观,更是提升代码内在质量、使其更易于理解和适应未来变化的关键实践。在日常开发中,持续关注代码质量,并适时进行重构,是构建健壮、可伸缩软件系统的重要组成部分。
以上就是代码重构:提升函数可读性与可维护性的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号