I have a zillion-line method somebody else wrote that I want to refactor using PhpStorm. Let's say that in highly abbreviated form, its basic structure looks something like this:
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;
}
If I try to take Branch Two and extract it into its own method, PhpStorm rightly complaints about inconsistent return points because of the early return.
So my question is: How do I keep doing an early return with my first HappyResponse
and still extract my verbose code into its own method? I thought about throwing and catching an exception for the early return, but since nothing is going wrong in that scenario, an throwing an exception felt like a really terrible smell.
Is there an easy way to make this type of thing work?
Since the overall structure is if/else if/...
you don't need to return in each branch. Each branch should assign the $output
variable that gets returned at the end.
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;
}
When you move the branch code into its own function, that function can return the $output
value, and you'll do
$output = new_function(...);