When doing internationalization in Java, you assign a string key to each message. What’s the best practice, on where to place those string keys. Goal is to allow easy refactoring (eg. key name changes), clean and readable code, separation of concerns but still no duplication of keys/messages even if called from different parts of the code.
//bad way, strings directly in code
messages.getString("hello_key");
–
// better way, use String constants
public static final String HELLO_KEY = "hello_key";
...
messages.getString(HELLO_KEY);
–
// other (better?) way, put all keys in one huge central class
public class AllMessageKeys {
public static final String HELLO_KEY = "hello_key";
...
}
public class Foo {
...
messages.getString(AllMessageKeys.HELLO_KEY);
}
–
// other (better?) way, put all keys in neighbor class
public class FooMessageKeys {
public static final String HELLO_KEY = "hello_key";
}
public class Foo {
...
messages.getString(FooMessageKeys.HELLO_KEY);
}
Any other proposals? Which is best? I’m on Eclipse IDE, if that makes the refactoring part any clearer.
Clarification: in the above examples “messages” is of type ResourceBundle.
i always using for such stuff an interface where my keys are listed. The name of the Interace is mostly DESC=Issue/short describtion/topic and the keys values.
This way you can make some nice Interface and some general Interface e.g. for OK or Abort keys.