Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intellij IDEA extract constant through entire project

Let's say I have a "magic string" in four classes and I want it to be replaced in all places by one constant from some constants class. (I'm speaking about Java/Groovy classes but any other languages would be helpful too.) The best solution I can think of is to extract the constant in one class and then use the Replace in Path dialog for the others. But that doesn't solve imports of the constants class and it's quite a lot of work. Is there a better way?

I've found this documentation page but there is no mention of this functionality.

like image 745
daerin Avatar asked Jan 05 '15 13:01

daerin


People also ask

How do I extract files in IntelliJ?

To extract method:Press Ctrl+Alt+M or from the main menu, select Refactor | Extract | Method. In the dialog that opens, configure a method options, such as visibility, parameters, and so on. You can also change a name of the method if you need. Click OK.

How do you extract variables?

Highlight the code you want to extract to a variable and press ⌥⌘V (macOS), or Ctrl+Alt+V (Windows/Linux), to extract it. Extracting parameters can be useful in improving the readability of your code.

How do I change all variables in IntelliJ?

Try to set cursor on variable and use shortcut Shift-F6 - after that there are dialog frame for change name of variable and it changes all occurences of variable to setted name.


2 Answers

A better way is to use the Find and Replace Code Duplicates... refactoring.

Extract the constant like normal and then invoke Find and Replace Code Duplicates... on the introduced constant. It can find all places in your project where the "magic string" is used and offers to replace it with a reference to the constant.

like image 124
Bas Leijdekkers Avatar answered Sep 18 '22 15:09

Bas Leijdekkers


This actually isn't so hard to do with the normal Replace in Path action.

Firstly, you need to go into Settings and enable this: Editor -> General -> Auto Import -> Add unambiguous imports on the fly

Now, create your constant in a class some place, and do a Replace in Path (ctrl-shift-R)

Text to find: "foo"

Replace with: Constants.FOO

Now, use Find and keep hitting Replace to change this magic value in all files except the Constants class where it is defined.

You should observe that the imports are automatically added in each file (given that the constant is unique).

like image 43
vikingsteve Avatar answered Sep 22 '22 15:09

vikingsteve