简体   繁体   中英

Good practices in spreading the locale object in a java program

I am currently making the internationalization of a program in spanish. I have the program structured following a MVC pattern.

The data objects, however, have some methods which are locale-dependent (for example, throwing exceptions when giving them incorrect data, with the specific error in the message).

The first solution in order to be the whole program locale-dependent is to pass the locale to these data objects, but it seems to me that it will break the MVC principle.

The second solution I thought was, for example, in case of a method of a data object returning a string, to return really the key of the string in the bundle, but this will lead to confussion because I have a bundle file for each package, and that method could be called from another package.

So, what would be the better approach to lead with this problem?

Thanks!!

If you can do

Locale.setDefault(locale);

Locale locale = Locale.getDefault();

with an optional parameter for DISPLAY (user interface) or FORMAT (numbers, currency).

MessageFormat and so on will then be right.

Where the text comes from is another story.

In general there are many projects with bundle per package, resulting in many bundles. That works when extracting the text in the same package.

For translation purposes these multiple packages are suboptimal: if for N languages the same duplicate texts pop up, or simply to translate concistently with same formulations. The solution for that is using a translation memory (like the tmx format). Perhaps most important is that some person should take responsibility on all translations, and keep things organized. Maybe in concord with documentation/help. Definitely write some checking tools, comparing translations for completeness and so on.

Just giving the translation key (plus bundle name?) seems just postponing the problem. In a form I did encounter such a usage for later internationalized logs: where users with several languages could read the data in their own language.

The answer: Use dependency injection when nice looking. Otherwise make global translation functions. With a trick a function call or better a field may find out its class (mind embedded/anonymous classes, lambdas) so a package bound "Bundle.properties" could be loaded per Default:

class T {
    MyTranslator i18n = new MyTranslator(); // Loads bundles
    ...
    i18n.t("This kind of {0} is {1}.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM