1

Today, I have a style question: Given the following code, should I be overriding Enum#toString() to present the application user a localized string or switch to a custom function (say, getLabel()) or is there another method to achieve the same effect?

I'm mainly after staying DRY here, so hardcoding the resource bundle prefix is not an option.

I have a simple enum like this:

public enum DUE_DATE {
   START,
   PRESENTED;

   public String toString() {
       return DBResBundle.instance().getString("due_date_lbl_" + name());
   }
}

where DBResBundle is my ResourceBundle implementation that I can access as msg in JSF like so:

<h:selectOneMenu value="#{m.due_date}" id="due">
  <f:selectItems value="#{dueDates}" var="d" 
    itemLabel="#{msg['due_date_lbl_'.concat(d.name())]}" />
</h:selectOneMenu>

I'm also using the the enum in code (not just JSF) context, but I don't utilize the toString() there.

mabi
  • 5,279
  • 2
  • 43
  • 78
  • 2
    Where would `toString()` find the locale used to retrieve the appropriate localized message? – JB Nizet Jul 18 '13 at 11:42
  • I would go for the `getLabel()`, because it can represent its semantics better in this case. The semantics of `toString()` isn't really defined and most of its use is for debugging. – JimmyB Jul 18 '13 at 11:51
  • @JBNizet it's currently fetching the locale from JSF's viewRoot. Which is admittedly bad design and will get a fallback to the currently logged in user's stored locale I have available elsewhere. – mabi Jul 18 '13 at 12:02
  • @HannoBinder yeah, the concern that prompted the question was that the JavaDoc for `Enum#toString()` says it's output should be programmer-readable, not end user readable. – mabi Jul 18 '13 at 12:04
  • 1
    Right. And that's why people would expect `toString()` to be just like that. Thus, good style will be *not* to use `toString()` for the UI or anything like that. – JimmyB Jul 18 '13 at 12:32
  • Besides, having the code of a functional enum tight to a particular view technology and singletons or threadlocals containing the locale is also a problem. Your object model shouldn't care about the view layer. – JB Nizet Jul 18 '13 at 13:04
  • Agree with the layer separation argument, which also rules out `getLabel()`. So maybe this is a duplicate of http://stackoverflow.com/q/15633007/785663 ? – mabi Jul 18 '13 at 13:29

1 Answers1

0

I've ended up with a method getMsgKey() on all of my enums that basically does

return getClass().getSimpleName() + "_" + name();

Which is just like Internationalization of multiple enums (translation of enum values) but without the EnumTranslator.

Community
  • 1
  • 1
mabi
  • 5,279
  • 2
  • 43
  • 78