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?
5
  • 8
    No, and No. .... Commented Dec 25, 2013 at 7:03
  • The JVM will combine all String literals used in the String literal pool no matter how many classes or Jars the string literal appears. Commented Dec 25, 2013 at 7:06
  • No, and No. ... Apart from internationalization Commented Dec 25, 2013 at 7:06
  • If you define your strings as constants (maybe in a separate class or store them in a special file), it would be easier to find and edit them. Sometimes VERY MUCH easier. Commented Dec 25, 2013 at 7:07
  • Though off topic, I felt this link, is worth noting. Commented Dec 25, 2013 at 8:00

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

  • Comments

    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.

    1 Comment

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

    Comments

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.