IntelliJ IDEA offers a comprehensive set of automated code refactorings that lead to significant productivity gains when used right. This page will teach you how to do that, starting from the basics. To learn more, refer to the section Refactoring Source Code.
In this section:
- String fragments
- Change variable type
- Invert boolean
- Type migration
- Essential refactoring shortcuts
- Other useful refactorings
- Refactor this
First of all, don't bother selecting anything before you apply a refactoring. IntelliJ IDEA is smart enough to figure out what statement you’re going to refactor, and only asks for confirmation if there are several possible choices:
Another important thing to know is that IntelliJ IDEA lets you undo everything, and that includes refactorings, no matter how complex code transformations they cause. Just press Ctrl+Z, and you're back to where you were before inadvertently scrambling a few thousands lines of code.
IntelliJ IDEA encourages you to use the keyboard instead of the mouse. It's proven to be faster and in the end will make you more productive at writing and transforming your code.
One thing that helps you easily use the keyboard to work with dialog boxes and popup windows is mnemonics, or the shortcut keys automatically assigned to each of the dialog elements. They are marked with an underscore. After you open a dialog, press Alt and an underscored character:
A real time saver is the ability to extract a part of a string expression with the help of the Extract... refactorings. Just select a string fragment and apply a refactoring to replace all of the selected fragment usages with the introduced constant or variable.
Change variable type
You can select a variable type when using the Extract variable refactoring. Press Shift+Tab when editing a variable name, and IntelliJ IDEA will offer you to select the variable type (e.g., you can tell it use the interface instead of implementation, or vice versa).
One basic but very helpful refactoring is the Invert Boolean, which inverts the semantics along with the data flow dependent expressions for any Boolean variable, parameter, field or method.
The Type Migration refactoring, as its name suggests, lets you automatically change the type for any class member, along with the dataflow-dependent type entries such as method return types, local variables, parameters, etc.
Essential refactoring shortcuts
- Rename: Shift+F6
- Copy class or file: F5
- Move class or file: F6
- Extract constant: Ctrl+Alt+C
- Extract variable: Ctrl+Alt+V
- Extract method: Ctrl+Alt+M
- Extract field: Ctrl+Alt+F
- Extract parameter: Ctrl+Alt+P
- Inline class or method: Ctrl+Alt+N
- Change signature: Ctrl+F6
Other useful refactorings
If you cannot recall the shortcut for a particular refactoring, or you're just not sure what to do next, simply use Refactor this by pressing Ctrl+Shift+Alt+T.
You will see the list of refactorings available in the current context.