Search code examples
javaintellij-ideaconstants

Find all String values that can be replaced by constants (static final) with Intellij IDEA


I'm trying to find all the places in a project where a constant could be introduced, because a String literal is being overused.

I'm aware of the Refactor > Introduce Constant... (Ctrl + Alt + C) function that Intellij has. But I can't find a way to search massively for these places where this function would make sense to be applied. Thanks


Solution

  • For IntelliJ Ultimate:


    For IntelliJ Community:

    By exploiting the localization (translation) feature, you can find all string duplicates... This isn't as robust as the Ultimate "duplicate code" feature -- which is capable of detecting duplicate code blocks -- but can help for quickly finding duplicates strings in a project.

    Preferences | Editor | Inspections | Java | Internationalization | Duplicate String Literal

    • Click the checkbox to enable ☑
    • Set the minimum string length value (it defaults to 5 characters)
    • Change the warning level to 🛑 Error

    Then navigate to View | Tool Windows | Problems and click the Project Errors tab.


    Disclaimer

    String.format("This probably goes without saying, but " +
       "be weary of over engineering your code, sometimes " + 
       "%s are %s when %s", 
       STRING_LITERALS, EASIER_TO_READ, JUST_TYPED_OUT);