Is it good practice to define private constant strings that have the same name as their values? Take the following code for example.
public class Example {
private static final String FIRST_KEY = "firstKey";
private static final String SECOND_KEY = "secondKey";
private static final String THIRD_KEY = "thirdKey";
private static final String SOME_KEY = "someKey";
private static final String SOME_OTHER_KEY = "someOtherKey";
private static final String BLAH = "blah";
public Map<String, Object> createMap() {
Map<String, Object> map = new HashMap<>();
map.put(FIRST_KEY, getFromDB());
map.put(SECOND_KEY, computeValue2());
map.put(THIRD_KEY, computeValue3());
map.put(SOME_KEY, "any value");
map.put(SOME_OTHER_KEY, new Object());
map.put(BLAH, new Object());
return map;
}
...
}
I believe this does not add any value when they are used only once (or maybe even twice). They are definitely harder to read when I'm checking some JSON generated content from the map. I need to jump to the constant definition to make sure that JSON key and map key are actually the same. This convention was used in many projects I worked on, and I have yet to understand why. Simpler refactoring should not be the reason as long as keys are not used too many times. It's overuse of string constants in my opinion. Private string constants are helpful, when their names really explain content but in this example they do not (and are basically just copies).
enum
.