
在软件开发中,随着业务逻辑的增长,函数可能会变得臃肿和难以理解。原始的execute函数展示了一些常见的问题:
针对上述问题,我们可以采用以下策略进行重构:
卫语句是一种通过提前返回来简化复杂条件逻辑的技术。它能有效减少嵌套层级,使代码路径更清晰。
重构前:
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 0;
}重构后:
立即学习“PHP免费学习笔记(深入)”;
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 0; // 或者返回1表示错误
}
// ... 后续逻辑 ...
}通过将主逻辑包裹在一个if语句中,然后在其外部处理错误情况,不如直接在条件不满足时返回。这种“先检查错误,再执行主逻辑”的模式使得正常流程的代码更靠前,更易读。
switch语句通常可以被多态或数据结构(如关联数组/映射)替代,尤其当分支逻辑只是根据一个变量的值来取用不同的数据时。
重构前:
switch ($this->drinkType) {
case 'tea':
if ($money < 0.4) { /* ... */ }
break;
case 'coffee':
if ($money < 0.5) { /* ... */ }
break;
case 'chocolate':
if ($money < 0.6) { /* ... */ }
break;
}重构后:
立即学习“PHP免费学习笔记(深入)”;
// 定义饮料成本映射,可以作为类成员变量或配置项
$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 0; // 或者返回1表示错误
}这种方法不仅消除了switch语句,使得新增饮料类型时只需修改$drinkCosts数组(或外部配置),而无需修改execute函数的核心逻辑,从而更好地遵循了开闭原则。
hasCorrectSugars负责验证糖量是否在有效范围内,而checkSugars负责根据糖量输出信息。它们职责明确,但execute函数中对它们的调用顺序和错误处理可以进一步优化。
重构前:
if ($this->hasCorrectSugars($input)) {
$this->checkSugars($input, $output);
return 0;
}
$output->writeln('The number of sugars should be between 0 and 2');
return 0;重构后:
立即学习“PHP免费学习笔记(深入)”;
// 如果糖量不正确,立即返回并输出错误信息
if (!$this->hasCorrectSugars($input)) {
$output->writeln('The number of sugars should be between 0 and 2');
return 0; // 或者返回1表示错误
}
// 糖量正确,则调用checkSugars进行信息输出
$this->checkSugars($input, $output);
return 0; // 如果是成功完成,返回0hasCorrectSugars的实现保持简洁,只负责验证:
protected function hasCorrectSugars($input): bool
{
$sugars = $input->getArgument('sugars');
// 假设 $this->minSugars 和 $this->maxSugars 已定义
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函数将变得更加清晰和易于维护:
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
// 假设这是一个Command类的一部分
class DrinkOrderCommand
{
protected string $drinkType;
protected array $allowedDrinkTypes = ['tea', 'coffee', 'chocolate'];
protected float $minSugars = 0;
protected float $maxSugars = 2;
// 假设 setDrinkType 和 isExtraHot 等方法已定义
protected function setDrinkType(InputInterface $input): void
{
$this->drinkType = $input->getArgument('drinkType'); // 假设有drinkType参数
}
protected function isExtraHot(InputInterface $input, OutputInterface $output): void
{
// 示例:根据输入判断是否额外加热并输出
if ($input->getOption('extra-hot')) { // 假设有extra-hot选项
$output->write(' (extra hot)');
}
}
protected function hasCorrectSugars(InputInterface $input): bool
{
$sugars = $input->getArgument('sugars');
return ($sugars >= $this->minSugars && $sugars <= $this->maxSugars);
}
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('');
}
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; // 错误返回非0
}
// 2. 使用映射替代switch:验证金额
$drinkCosts = [
'tea' => 0.4,
'coffee' => 0.5,
'chocolate' => 0.6
];
$money = (float)$input->getArgument('money'); // 确保金额是浮点数
// 检查是否存在该饮料类型的成本,虽然in_array已检查,但这里更严谨
if (!isset($drinkCosts[$this->drinkType])) {
$output->writeln('Error: Unknown drink type cost configuration.');
return 1;
}
$drinkCost = $drinkCosts[$this->drinkType];
if ($money < $drinkCost) {
$output->writeln('The ' . $this->drinkType . ' costs ' . $drinkCost);
return 1; // 错误返回非0
}
// 3. 卫语句:验证糖量
if (!$this->hasCorrectSugars($input)) {
$output->writeln('The number of sugars should be between 0 and 2');
return 1; // 错误返回非0
}
// 4. 执行成功后的输出逻辑
$this->checkSugars($input, $output);
return 0; // 成功返回0
}
}通过应用卫语句、利用数据结构替代switch语句,并明确函数职责,我们成功地重构了一个复杂且难以维护的PHP函数。重构后的代码不仅提高了可读性和可维护性,也更好地遵循了SOLID原则,为未来的功能扩展和代码演进奠定了坚实的基础。在实际开发中,持续的代码审查和重构是提升软件质量的关键实践。
以上就是如何重构PHP函数:消除Switch语句与优化验证逻辑的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号