PhpStorm重构含提前返回的分支方法:解决返回点不一致问题
重构含提前返回的PHP分支方法(PhpStorm)
问题场景
现有一个数千行的PHP方法,简化结构如下:
myMethodName($input){ if ($input === self::STRING_THAT_PROMPTS_ERROR) { //Branch One return new ErrorResponse('You messed up.'); } elseif ($input === self::HAPPY_STRING_ONE) { //Branch Two if(!$someOtherThing) { return new HappyResponse('Some other thing made us happy-happy.'); } //We do lots of verbose stuff here and then, finally ... $output = new HappyResponse('some value'); } elseif ($input === self::HAPPY_STRING_TWO) { //Branch Three //We do lots of verbose stuff here and then, finally ... $output = new HappyResponse('some other value'); } else { //Branch Four return new ErrorResponse('Oh no, default.'); } return $output; }
尝试将分支二的冗长代码提取为独立方法时,PhpStorm因提前返回提示返回点不一致,且不想用异常(无实际异常场景,属于代码异味),需寻找简便重构方案。
解决方案
方案1:仅提取冗长代码段(保留原提前返回)
这种方式最直接,无需改动原方法的提前返回逻辑,只把分支二中的冗长业务代码单独提取:
- 选中分支二中
//We do lots of verbose stuff here and then, finally ...到$output = new HappyResponse('some value');的代码段 - 在PhpStorm中使用快捷键
Ctrl+Alt+M(Windows/Linux)或Cmd+Alt+M(Mac)触发提取方法操作 - 给新方法命名(比如
processHappyStringOneVerboseLogic),确保方法返回HappyResponse类型 - 替换原分支二的冗长代码为新方法调用,最终分支二代码变为:
} elseif ($input === self::HAPPY_STRING_ONE) { //Branch Two if(!$someOtherThing) { return new HappyResponse('Some other thing made us happy-happy.'); } $output = $this->processHappyStringOneVerboseLogic(); }
这种方式完全保留原提前返回逻辑,PhpStorm不会再提示返回不一致问题。
方案2:重构整个分支逻辑(消除中间变量$output)
如果想让整个方法结构更清晰,可去掉中间变量$output,让所有分支直接返回结果,这样能完整提取分支二的全部逻辑:
- 先修改分支三的代码,把给
$output赋值改为直接返回:
} elseif ($input === self::HAPPY_STRING_TWO) { //Branch Three //We do lots of verbose stuff here and then, finally ... return new HappyResponse('some other value'); }
- 删除方法末尾的
return $output;语句 - 选中分支二的全部代码(从
if(!$someOtherThing)到$output = new HappyResponse('some value');),触发提取方法操作,命名为handleHappyStringOne,方法返回HappyResponse类型 - 原分支二替换为方法调用并直接返回:
} elseif ($input === self::HAPPY_STRING_ONE) { return $this->handleHappyStringOne(); }
提取后的新方法如下:
private function handleHappyStringOne(): HappyResponse { if(!$someOtherThing) { return new HappyResponse('Some other thing made us happy-happy.'); } //We do lots of verbose stuff here and then, finally ... return new HappyResponse('some value'); }
这种方式让整个原方法的分支逻辑更统一,所有分支均直接返回结果,后续维护和重构也更方便。
内容的提问来源于stack exchange,提问作者Viscountess of the Junkyard
相关产品推荐
相关产品推荐

