10

I'm running into issues with an approach I am taking and am now wondering if I just started down the wrong path and should rethink my approach. Here is what I attempting.

I would like to use an Enum to represent different possible Account Statuses (there are other finite data sets that I will be setting up using a duplicate approach):

  • A, Active
  • I, Inactive
  • P, Pending

Those Account Statuses must be presented to the user in their language if preference.

Example: Account Status is A, show it as Active for English speakers and Activo for Spanish.

There are also situations where I would like to show a dropdown list of all possible Account Statuses in the appropriate locale preference.


Current Approach

Use an AccountStatusEnum class with values of (A,I,P).

In a private static member variable store an EnumMap of localized Account Statuses inside a EnumMap of possible Locales.

Example:

private static EnumMap<LocaleEnum, EnumMap<AccountStatusEnum, String>> localeAccountStatuses = new EnumMap<LocaleEnum, EnumMap<AccountStatusEnum, String>>(LocaleEnum.class);

This would get loaded within a static initialization block.

I could then use the following methods to get all the values for a dropdown:

public static EnumMap<AccountStatusEnum, String> getAccountStatuses(LocaleEnum locale) {
        return localeAccountStatuses.get(locale);
    }

Or I could use this method to get a single description for a given Enum:

public String getDescription(LocaleEnum locale){
            return getAccountStatuses(locale).get(this);
        }

Example Usage: AccountStatusEnum.A.getDescription(LocaleEnum.es_MX);

I'm curious about your thoughts on this approach and possible better approaches for accomplishing the same thing.

EDIT The logic to get the values to populate the Enums would be centralized within a single helper class. Therefore if the source of the descriptions changes to come from a new source, the code change is minimized.

Thanks

forevernewb123
  • 101
  • 1
  • 1
  • 5

3 Answers3

17

I would approach this problem as I would approach any localization issue: ResourceBundle. I use a class called I18n that has a static method called getMessage that takes a key and optionally a list of arguments. The key gets looked up in a ResourceBundle configured to use the default Locale or whatever you prefer (specifics here aren't important, so long as the caller to I18n doesn't have to know about what the Locale is).

The I18n class is as follows:

public final class I18n {
    private I18n() {
    }

    private static ResourceBundle bundle;

    public static String getMessage(String key) {
        if(bundle == null) {
            bundle = ResourceBundle.getBundle("path.to.i18n.messages");
        }
        return bundle.getString(key);
    }

    public static String getMessage(String key, Object ... arguments) {
        return MessageFormat.format(getMessage(key), arguments);
    }
}

In your project, you would have in package path.to.i18n, files containing messages.properties (default), messages_en.properties (Locale en), messages_it.properties (Locale it), etc.

When you need to translate an enum value, you shouldn't have to treat it any differently than any other key, except the key is the enum term.

In other words, you have:

public enum AccountStatusEnum {
  Active,
  Inactive,
  Pending
}

When you call I18n.getMessage, you pass with AccountStatusEnum.Active.toString() and the translation will be found in a property file with key "Active". If you're like me, and you prefer to use lower-case keys, then you should perform toLowerCase() on the string. Better still, you create a new I18n.getMessage that takes an Enum rather than a key, and that method calls the String version of I18n.getMessage with the enum value converted to string and in lowercase.

So you'd then add this to the I18n class:

    public static String getMessage(Enum<?> enumVal) {
        return getMessage(enumVal.toString().toLowerCase());
    }

I prefer to use this method because it incorporates the same translation logic in the same part of the program without impacting your design. You may even want to differentiate enum keys from your other keys, in which case you can begin each enum key with "enum.", so you would prepend "enum." when calling getMessage. Just remember to name your keys in your properties files accordingly.

I hope that helps!

Niklas H
  • 645
  • 5
  • 15
Neil
  • 22,670
  • 45
  • 76
1

ResourceBundle is the way to go, but I would take advantage of the fact that enums are objects, and hide the details of i19n inside

public enum MyEnum {
  A,
  I,
  P;

  private String localeText = null;

  private MyEnum() {
    // Load resource bundle
    this.localeText = // get message;
  }

  public String getLocaleText() {
    return this.localeText();
  }
}

That would allow you to do:

MyEnum.A.getLocaleText();

directly, everywhere

An optimization would be loading the resource bundle as an static attribute, in an static initializer.

And in JEE, bonus points for making the resource bundle injectable (so you may change the localization strings easily).

SJuan76
  • 2,532
  • 1
  • 17
  • 16
  • 2
    My personal preference would be to keep l18n in one place in the program. Otherwise why wouldn't you apply this logic on any other class with its own `getLocaleText`? Though, I suppose it is subjective. To each his own. – Neil Sep 21 '14 at 10:33
  • I feel putting localization to your enum breaks single responsibility principle. It isn't that convenient in the long run since you have to have localization on so many different stuff that you risk code duplication and massive effort if you want to change anything about your localization code. – palto Sep 21 '14 at 10:51
  • The idea of having the i18n within the enum is that it encapsulates how i18n is implemented. If I have a bunch of enums, and then a separate i18n helper class, then a change to the i18n would require a change at each usage of the helper instead of a change within the initialization of the enums. – forevernewb123 Sep 21 '14 at 14:26
  • getMessage() will need to take 3 parameters, String prefix, Enum > code, EnumLocale locale. Example: `getMessage("user.status.", UserStatusEnum.A, LocaleEnum.en_US)`, this is necessary if getMessage() is left generic. This requires every caller to essentially know how to construct the key as opposed to hiding that with the enum that represents the values. I could make a getMessage() method per enum, getAccountStatusMessage(), to hide this, but then I'm starting to spread the code around that knows about particular enums as opposed to encapsulating it within the enum itself. – forevernewb123 Sep 21 '14 at 14:39
  • If I make a change to how I am implementing i18n, say by moving the values to a data store instead of from a properties file, then I'm either changing the initialization of a bunch of enums (guaranteed) OR I'm changing the single i18n class that implements the getMessage() method and (potentially) every place that calls getMessage() depending if the signature changes. (So these are the points for dealing with potential changes.) – forevernewb123 Sep 21 '14 at 14:48
  • Palto, I agree one problem with implementing this in the enums is that you could have a lot of duplicate code in your enums to get the messages from the ResourceBundle. So what if the i18n class was used to centralize that logic, but instead of using it throughout the entire application to get the messages, it was instead used in the initialization of enums? This would leave the enums to know how to generate their own key and if the implementation was changed to go to a data store, that change would only be within the i18n class. That should provide encapsulation and reduce duplicate code. – forevernewb123 Sep 21 '14 at 14:56
  • @forevernewb123 Generally you don't want to change the locale every other call. If the user switches language, you set the locale of the resource bundle and continue. If you want that level of flexibility, then add `getMessage` that also takes `Locale`, though I wouldn't recommend it. If you wanted, say, a list in many different languages, then you'd still have to know *which* languages at that point. You can't generalize something that isn't generalizable, so *something* must remain constant between calls that you can optimize. If it isn't the locale, what is it? – Neil Sep 21 '14 at 15:49
  • @Neil if your code is a program, a single bundle is ok. OTOH, if it is a component, making that simple bundle may be troublesome (getting from somewhere in the docs -if they exist- which keys are needed, hoping that they do not conflict with some other component keys, and then writting down the actual file). A bundle in the same package than the class will avoid all of that. – SJuan76 Sep 21 '14 at 16:03
  • @SJuan76 A bundle handled internally to your enum class would suffer the same problems unless the enum has its own package, however each enum having its own localization files is a bit of an overkill here. There is nothing keeping you from turning `L18n` into a non-static class and handling multple `L18n` instances, one for each bundle if that's desired. I tend to use one bundle per project though. – Neil Sep 21 '14 at 16:22
  • 1
    @Neil a given user won't change locales between each request, but for my web app, the requests coming from different users could come for different locales. The application would need to be able to switch between locales based on a given user's preference. – forevernewb123 Sep 21 '14 at 23:26
  • @Neil just an fyi, i18n or L10n stand for internationalization and localization respectively. The terms are frequently abbreviated to the numeronyms i18n (where 18 stands for the number of letters between the first i and last n in internationalization, a usage coined at DEC in the 1970s or 80s)[1] and L10n respectively, due to the length of the words. -- per Wikipedia :^) – forevernewb123 Sep 21 '14 at 23:28
  • @forevernewb123 Heh, I've had it wrong all these years. I was familiar with the terms, just never really given it any thought. Thanks for bringing that to my attention. – Neil Sep 22 '14 at 07:40
  • Thanks for the help. I'm curious how the votes will turn out over time. So far Neil, you are in the lead. :^) – forevernewb123 Sep 23 '14 at 22:29
  • Naming the enum instances `A`, `I`, and `P` is awful. – David Conrad Jul 26 '16 at 03:31
1

Summing up pros and cons of the proposed answers:

The problem with the global helper file is the lack of flexibility, for example, in an application I have various enums with a specific enum constant that I would like to have a very specific key, not following the common format.

The problem with locating the logic in the enums is the replication of code, which in turn would make it harder to maintain in the long run

With Java 8 we have at our disposal a very helpful feature that can be very helpful in solving the problems discussed above: default methods.

My proposal is to have an interface with a single method to obtain the keys:

public interface I18nEnum {
   default String getMessageKey(Enum<?> e) {
      return e.getClass().getSimpleName() + '.' + e.name().toLowerCase();
   }
}

That way our enums simply have to declare they implement that interface, without actually implementing it, and we have the benefits of having our code in a single place, but we still have the flexibility to handle specific cases by overriding the default method when needed, for example:

public enum Sex implements I18nEnum {
    MALE,
    FEMALE,
    UNKNOWN {
        @Override
        public String getMessageKey(Enum<?> e) {
            return "Common.UNKNOWN";
        }
    }
}
magomar
  • 111
  • 2