Home » IntelliJ IDEA Code Refactoring

IntelliJ IDEA Code Refactoring

by Online Tutorials Library

IntelliJ Code Refactoring

Refactoring is the process of changing the structure of the existing program without changing its functionality and usage. Refactoring also used to improve the code reusability, increase performance and also remove the duplicate functionality or unused functionality. Refactoring is a task that should be performed very carefully because a single mistake could generate a lots of bugs.

In the refactor menu, we can find all possible refactor option. There is also a shortcut option available for the refactoring. “Ctrl+Alt+Shift+T” shortcut will open a pop-up which shows all the refactoring options available for the piece of code where the cursor is hovering over.

Some of the important Refactoring option are as follows:

  • Rename
  • Copy Refactoring
  • Move Refactroing
  • Safe Delete
  • Find and Replace Code Duplicates

Rename

This action provides facilities to rename methods, attributes, parameters and so on. Here, we will create an example with class name Person.

Now we will change the name of Person class with Employee then it will modify the constructor and main() method. To do this, follow the below steps:

  • Select Person Word
  • In the menu bar, go to Refactor -> Rename. Following screen appears. Change the name and click on Refactor Button.

IntelliJ IDEA Code Refactoring

Copy Refactoring

This action is used to copy one class to another. It can be done in the existing one or a new one. To do this, follow the below steps:

  • Go to Refactor -> Copy. Below screen appears.

IntelliJ IDEA Code Refactoring

  • Enter the New name, Select Destination package and click Ok button.

Move Refactoring

It is the facility which provides us to move a file to another place or make an inner class of another class. To do this, follow the below steps:

  • Go to Refactor -> Move. Below screen appears.
  • Provides the destination. Click Refactor.

IntelliJ IDEA Code Refactoring

Safe Delete

This option will delete the Object, Class, Method, Interface, Parameter etc. only when it is not referenced anywhere in the project. To do this, follow the below steps:

Type the below code in the editor and select “sayHi”

Now Go to Refactor -> Safe Delete

If the sayHi method is used anywhere than it will show on the below screen.

IntelliJ IDEA Code Refactoring

Find and Replace Code Duplicates

This refactoring option identifies the duplicate codes similar to the selected method or constant field and replaces it with a suitable code. To do this, follow the below steps:

  • Type the below code, position the cursor whose duplicates we want to search.
  • Go to Refactor -> Find and Replace Code Duplicates
  • Dialog Box Open, select the scope where IDE will look for the duplicates

IntelliJ IDEA Code Refactoring

  • After Refactoring, it gives confirmation message, Click Refactor. Output is:

You may also like