我想询问有关 Java 良好编码实践的问题。我想创建一些属性的枚举并重写 toString()
以按以下方式使用它(使用 JSF 1.2
来检索本地化消息):
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
定义中是否合适?如果没有,我想了解为什么以及如何做得更好。
最佳答案
这里有两点需要说明:
如果默认情况(在代码中返回 null)是运行时错误,那么使用
switch
很容易出错。我认为有两种更好的选择:- 使用字段
localizationKey
,在枚举实例的构造函数中初始化,并在toString
方法中引用此键 - 或者,(对于更复杂的情况)使
toString
抽象并强制每个实例使用正确的实现进行覆盖。请参阅this question例如。
- 使用字段
许多人认为
toString
要么用于真正明显的实现,要么仅用于调试。 (有关详细说明,请参阅 this question。)我的建议:提出一个更具描述性的方法名称,不要为了方便而重复使用toString
。
更新:稍微缩小一下 Java 语义:这个逻辑属于 View 而不是模型,正如 BalusC 在下面的评论中指出的那样。
关于java - Enum 的 toString 方法和 Java 良好实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28693572/