0

I saw a Java article that said it's better to use string constant in annotations (you can see the article here). Why is that a good practice?

2 Answers 2

3

The most obvious use would be that finding all references to the constant is easier than finding all occurrences of the string. Your IDE will immediately help you with the former, but the latter you need to do yourself.

Then, there's also the issue of maintainability in case you need to change the value (consistently, everywhere).

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah but the strings of annotations are somehow fixed : if you type @SuppressWarnings("unchecked") the unchecked String must be and will be exactly the same string for like almost forever...
@spauny Your link shows good examples where the string is more like a true parameter, e.g. for configuring an email address.
1

Using constants is always better than direct use of string literals because information should be in code only once. If you use literal "foo" in 2 different locations there is a chance that you change one of the places and forget to change another. This may break your code.

The same and even more important in annotations. Annotations often are relevant for certain environment only. In ideal world we have 100% test coverage, so the problem will be found fast. In real life unit tests often run in environment that do not depend on some of the annotations written in code, so you will see problem on real environment only that could be tool late.

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.