我想请教一下在Java中良好的编码习惯。我想创造一些属性的enumeratoin并覆盖toString()
下面的方式来使用它(JSF 1.2
是为了用于检索本地化消息):枚举的toString方法和Java的良好做法
package ua.com.winforce.casino.email.util;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;
public enum StatisticItems {
MESSAGES,
VIEWS;
private static String BUNDLE_NAME = "messages";
public String toString(){
switch (this) {
case MESSAGES:
return getLocalizedMsg("messages.title");
case VIEWS:
return getLocalizedMsg("views.title");
default:
return null;
}
}
private static String getLocalizedMsg(String key, Object... arguments) {
Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
String resourceString;
try {
ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME, locale);
resourceString = bundle.getString(key);
} catch (MissingResourceException e) {
return key;
}
if (arguments == null) {
return resourceString;
}
MessageFormat format = new MessageFormat(resourceString, locale);
return format.format(arguments);
}
}
我的问题是关于很好的做法。把所有这些方法放在enum
定义中是否被认为是好的?如果没有,我想了解为什么,当然如何做得更好。
Downvoter,为什么downvote? – user3663882 2015-02-24 10:42:37
似乎是一个糟糕的主意,因为有一个'toString()'方法足够复杂,以至于当您试图打印调试消息时它可能会引发异常。 – khelwood 2015-02-24 10:45:10
在未来的JSF相关问题中,最好不要标记[java]。没有一个回答者考虑了'FacesContext',在JSF上下文中这两个回答在技术上都是错误的。而且,您最好在codereview.se上发布代码审查请求,而不是在SO上。或者至少从问题中消除主观性/论证性(包括像“最佳实践”这样的词)。对于真正的答案,请使用三个简单的关键字“jsf”,“enum”“localization”进行搜索。我以前回答过这种问题。 – BalusC 2015-02-24 11:18:37