PhpStorm refactoring tutorial , part 1

PhpStorm like all JetBrains IDEs has o lot of built in features. And you can add even more with plugins. It provides many refactoring features.

This will be a first part of refactoring tutorial.

We will start from the simple things.

Lesson 1: Extracting a variable and renaming it.

Example code to be refactored:

'use strict';

$('#container').addClass('example');

$('#container').on('click', function () {
    alert('hello');
});

$('#container').remove();

This code is bad. If you use jQuery object more than once, assign it to variable.

First let’s extract variable. Move cursor to any occurrence of $(‘#container’) in the code and press ctrl+r. Menu will appear, now select Extract variable. IDE gives you ability to replace all occurrences or just the highlighted one. We want to replace all of them. Choose it. Now we have ability to name the variable. IDE suggest names by the code, in most cases it gives  correct name, but we can change it :).

Code after refactor:

'use strict';

var $container = $( '#container' );
$container.addClass('example');

$container.on('click', function () {
    alert('hello');
});

$container.remove();

Next thing. We have extracted the variable but later we decide that current name is not obvious. Naming is very important so we want to change it. Move cursor to any occurrence of variable $container and again press +r (on Mac) or ctrl+r (on other os). In the menu choose first position, Rename. Place a new name in the popup and do refactor.

'use strict';

var jQueryContainer = $( '#container' );
jQueryContainer.addClass('example');

jQueryContainer.on('click', function () {
    alert('hello');
});

jQueryContainer.remove();

You have ability to search the whole project for occurrences of the variable name in the string / comment and text . Try it by yourself, it’s very handy :).

That’s all for today. See you in the next part.