Working With Switch and If Statements in PhpStorm 2016.1

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:

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

About Gary Hockin

Gary Hockin has been creating code to power web applications for 15 years, the last three of them at an extraordinary level. He is handsome, talented, funny and articulate, and also extremely modest. Gary is a valued contributor to Zend Framework 2 and is a member of the community review team. He's married and has two wonderful children, and when he's not coding, writing about code, speaking about code or reading about code, he can usually be found in the pub playing pool.
This entry was posted in Cool Feature and tagged , , . Bookmark the permalink.