class Constant {
public static final String ALBUM = "album";
public static final String NAME = "_name";
public static final String DISPLAY_NAME = "display-name";
public static final String SERVICE_NAME_METRIC_NAME_PREFIX = "service_name.metric_name";
}
Here is a public example of this practice I could find: https://developer.android.com/reference/android/provider/MediaStore.MediaColumnsI could understand that this might help in 2 ways refactoring and typo. This reduces chance of typo because you'll get compile error instead of run-time error if you typo a constant. This might also help in refactoring if you ever wants to change the value. but if may use this android public API example, I don't think it's wise to change a field name ever. If it's decommissioned, it's good to keep it so we don't re-use the field. If it's a new better field available, I think it should have a different name. I maybe making a straw man argument here. Let me know. If it's an internal API where such refactoring might make sense -- I still kind of think internal API should also be backward compatible, replacing a string are not a complicated operation in my opinion.
I see that this practice has a cost. One being that in every class that use this API. You need to add an import. It's also often the const is only used once from my experience.
import static com.example.MediaFields.NAME;
import static com.example.MediaFields.DISPLAY_NAME;
String value = json.getString(NAME);
String value2 = json.getString(DISPLAY_NAME);
vs String value = json.getString("name");
String value2 = json.getString("display_name");
You write 1 line for declaration plus 2 lines for each class using this API.
This is not a big deal in terms of LoC and I'm not an LoC police.
However, my sense is the cost outweigh the benefit.What do you think?
lanna•1h ago
It is also for documentation. With the declared constants, we know all possible values. With plain strings, how am I supposed to know which values to use?
The benefits far outweigh the marginal cost.