10

My perception for defining string constants in Java is that one should define a string constant, when the same string is used at multiple places. This help in reducing typo errors, reduce the effort for future changes to the string etc.

But how about string that are used at a single place. Should we declare string constant even in that case.

For eg. Logging Some counter (random example).

CounterLogger.addCounter("Method.Requested" , 1)
  • Is there an advantage of declaring constant rather than using raw string?
  • Does the compiler does any optimization?
Keen Sage
  • 1,899
  • 5
  • 26
  • 44

4 Answers4

4

Declaring constants can improve your code because they can be more descriptive. In your example

CounterLogger.addCounter("Method.Requested" , 1)

The method parameter "Method.Requested" is quite self describing but the 1 is not making this a constant would make this example more readable.

CounterLogger.addCounter("Method.Requested" , INITIAL_VALUE)
Alex Edwards
  • 1,613
  • 3
  • 24
  • 48
2

The way I see it, Strings can be used in one of two ways:

  • As properties / keys / enumerations - or in other words, as an internal representation of another Objects/states of your application, where one code component writes them, and another one reads them.
  • In UI - for GUI / console / logging display purposes.

    I Think it's easy to see how in both cases it's important to avoid hard-coding.

    The first kind of strings must (if possible) be stored as constants and exposed to whichever program component that might use them for input/output.

    Displayed Strings (like in your Logger case) are strings that you might change somewhere in the future. Having them all stored as static final fields in a constants-dedicated class can make later modifications much easier, and help avoid duplicates of similar massages.

    Regarding the optimization question - as others have already answered, I believe there's no significant difference.

  • Elist
    • 5,313
    • 3
    • 35
    • 73
    1

    Presumably, you'll want to write a unit test for whichever method contains that line of code. That unit test will need access to that String value. If you don't use a constant, you'll have the String repeated twice, and if you have to change it in the future, you'll have to change it in both places.

    So best to use a constant, even though the compiler is not going to do any helpful optimisations.

    Dawood ibn Kareem
    • 77,785
    • 15
    • 98
    • 110
    • I disagree. The unit test should only know about the String constant to use if it was a parameter to a method being tested. In that case the unit test needs to be explicit about what string value to use. If somebody goes to the implementation class and changes the constant the tests should break and force the developer to review them and update them to acknowledge that the interface to this class is now changing. – Iker Jimenez Jan 09 '18 at 16:58
    1

    In my view in your case is fine. If you cant see any advantage in declaring it as a constant dont do it. To support this point take a look at Spring JdbcTemplate (I have no doubt that Spring code is a good example to follow) it is full of String literals like these

    Assert.notNull(psc, "PreparedStatementCreator must not be null");
    Assert.notNull(action, "Callback object must not be null");
    throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
    

    but only two constants

    private static final String RETURN_RESULT_SET_PREFIX = "#result-set-";
    private static final String RETURN_UPDATE_COUNT_PREFIX = "#update-count-";
    

    Iterestingly, this line

    Assert.notNull(sql, "SQL must not be null");
    

    repeats 5 times in the code nevertheless the authors refused to make it a constant

    Evgeniy Dorofeev
    • 133,369
    • 30
    • 199
    • 275