Andrei
Andrei

Reputation: 5647

Most used Strings in IntelliJ

Is there a way to detect, if any hard-coded string is repeated more than x times in the whole project?

Let's say I have a project with multiple folders and classes and I have a separate class called Constants, where I store all my project constants. Since the project is getting bigger, it will be nice to have a possibility to detect repeated strings in the project. Of cource, it could be also manually done, but probably it exists already in IntelliJ or somewhere else.

Example:

instead of:

class A {
    String dog = "dog";
    String cat = "cat";
    String animals = dog + cat;
}

class B {
    String dog = "dog";
    String horse = "horse";
    String animals = dog + horse;
}

I am trying to make:

class A {
    String cat = "cat";
    String animals = DOG + cat;
}

class B {
    String horse = "horse";
    String animals = DOG + horse;
}

class Constant {
    static final String DOG = "dog";
}

It is oversimplified, but I hope the point is clear.

Upvotes: 1

Views: 133

Answers (1)

LppEdd
LppEdd

Reputation: 21172

The search part can be accomplished in four ways.
However only the second one is able to extract the new constant automatically.

  • Using the Find in path dialog, using a configuration similar to the below one.
    All the entries will be listed under Preview.

enter image description here


  • Using the Extract constant functionality (limited to the current file).

enter image description here

A new popup will appear, with the option Replace all occurrences

enter image description here

Using the designated shortcut (e.g. Ctrl+Alt+C) or Enter, another dialog will appear, and you'll be able to see the occurrences count.

enter image description here


  • Using a specific inspection, which is Duplicate String literal.
    You'll be able to run it via Analyze > Run inspection by name.

enter image description here

A new dialog will appear, which lets you customize the search criteria

enter image description here


  • Structural Search (docs).
    Unfortunately I'm not knowledgeable about it.

Upvotes: 3

Related Questions