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.
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With