Working With Switch and If Statements in PhpStorm 2016.1

Posted on by Gary Hockin

We’re all told that great developers refactor often (I looked for a quote on who said that, but couldn’t find anyone, so now it’s mine). Refactoring can be a tedious job, but PhpStorm’s intentions can help you break away from the tedium and get the task done quicker.

New in PhpStorm 2016.1 are a couple of intentions specifically designed to make refactoring between switch and if statements as painless as possible.  Let’s consider this code:

$name = 'Luke';

if ( $name == 'Luke' ) {
    $type = 'Jedi';
} elseif ( $name == 'Vader' ) {
    $type = 'Sith';
} elseif ( $name == 'Jar Jar') {
    $type = 'Fool';
} else {
    $type = 'Unknown';
}

This code is not the nicest-looking in the world; arguably it would be better suited to a switch statement. Thankfully, in the latest version of PhpStorm flipping between switch and if is easy thanks to the new intention.

Here you can see that we use the Quick-fix keyboard shortcut (Alt + Enter on Windows/Linux, Cmd + Enter on Mac) to see what intentions we can invoke at the location of the caret. We pick “Replace ‘if’ with ‘switch'” and voila, our complex if statement is replaced with a nice, readable switch statement.

We can also convert theswitch back to an if/else by invoking the opposite intention in exactly the same way.

Give it a try and let us know what you think. We’re also interested to hear what other refactoring intentions you’d like to see in the future.

– Gary and the PhpStorm Team

The Drive to Develop

Subscribe

Subscribe for updates