纠正不一致的返回点

问题描述 投票:0回答:1

我有一个其他人写的无数行方法,我想使用 PHPStorm 进行重构。假设以高度缩写的形式,其基本结构如下所示:

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 会正确地抱怨由于提前返回而导致返回点不一致。

所以我的问题是:如何继续使用第一个

HappyResponse
提前返回,同时仍然将详细代码提取到自己的方法中?我考虑过抛出并捕获异常以提前返回,但由于在这种情况下没有任何问题,抛出异常感觉就像是一种非常可怕的气味。

有没有一种简单的方法可以让这种事情发挥作用?

php exception architecture refactoring phpstorm
1个回答
0
投票

由于整体结构是

if/else if/...
,所以不需要在每个分支中都返回。每个分支都应该分配最终返回的
$output
变量。

function myMethodName($input){
    if ($input === self::STRING_THAT_PROMPTS_ERROR) {
        //Branch One
        $output = new ErrorResponse('You messed up.');
    } elseif ($input === self::HAPPY_STRING_ONE) {\
        //Branch Two
        if(!$someOtherThing) {
            $output = new HappyResponse('Some other thing made us happy-happy.');
        } else {
            //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
        $output = new ErrorResponse('Oh no, default.');
    } 
    return $output;
}

当您将分支代码移至其自己的函数中时,该函数可以返回

$output
值,您就可以了

$output = new_function(...);
© www.soinside.com 2019 - 2024. All rights reserved.