7

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

15

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!

  • shouldn't getMessage(...) return the String? – Lealem Admassu Jul 19 '16 at 8:09
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).

  • 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
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";
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.