我想问一下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语义:正如BalusC在下面的注释中指出的那样,该逻辑属于视图而不是模型。