Intellij IDEA extract constant through entire project
Asked Answered
P

2

6

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.

Pilliwinks answered 5/1, 2015 at 13:58 Comment(3)
IntelliJ won't do what you want in this case. BTW: Constants classes are usually deemed very poor design, so perhaps you want to rethink your approach.Election
@SoftwareEngineer can you provide a reference on why Constant classes are considered poor design?Lander
I only found this and this which both talk about Interfaces and mention Classes as better alternativeLander
F
6

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.

Floristic answered 7/7, 2015 at 10:13 Comment(3)
This sounds reasonable but doesn't seem to work for me.Kurtkurth
Sorry to hear that. Maybe submit a bug report with a little more information? youtrack.jetbrains.comFloristic
(Funny, just ran into this again, googled, and found this :) If you select the whole constant name, then invoking Find and Replace Code Duplicates seems to do nothing. If instead you just place your cursor somewhere in the constant, then it starts the refactoring as expected. Confusing!Kurtkurth
S
2

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).

Stedt answered 6/1, 2015 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.