- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有一天我听说我们应该使用枚举而不是常量。在所有情况下都可能吗? 枚举是否替代了常量?
在下面的示例中,我在常量文件中定义了常量,ConstantsTest 使用它们
public final class Constants {
private Constants(){
}
public static final String ACCOUNT="Account";
public static final String EVENT_ITEM ="EventItem";
public static final int MULTIPLIER_ONE = 1;
public static final int MULTIPLIER_NEGATIVE_ONE = -1;
public static final String BALANCE_AFTER_MODIFICATION = "BalanceAfterModification";
public static final String COMMA = ",";
public static final String DOTPSV =".psv";
public static final String NEW_LINE = "\n";
}
// Test Class
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ConstantsTest {
private static File rootDir = new File(".");
public static void main(String[] args) throws IOException {
Map<String,Integer> accountBalance = new HashMap<String, Integer>();
accountBalance.put("123",55000);
accountBalance.put("223",15000);
writeToFile(Constants.ACCOUNT, accountBalance, true, 2000);
// do operation
}
/**
*
* @param fileType
* @param inputData
* @param add if true add balance else substract the balance
* @return
* @throws IOException
*/
private static File writeToFile(String fileType , Map<String,Integer>accountBalance ,boolean add, int amount) throws IOException{
File file = null;
FileWriter fw = null;
try{
if(Constants.ACCOUNT.equals(fileType)){
file = new File(rootDir,Constants.ACCOUNT+Constants.DOTPSV);//creating a fileName using constants
fw = new FileWriter(file);
fw.write(Constants.ACCOUNT+Constants.COMMA+Constants.BALANCE_AFTER_MODIFICATION);//Writing Header in file using constant values
updateBalance(accountBalance, add, amount);
for(String key:accountBalance.keySet()){
fw.write(Constants.NEW_LINE);
fw.write(key+Constants.COMMA+accountBalance.get(key));
}
}
else if(Constants.EVENT_ITEM.equals(fileType))
{
// write to EventItem.psv
}
} finally{
if (null!=fw){
fw.close();
}
}
System.out.println("File created successfully");
return file;
}
private static void updateBalance(Map<String, Integer> accountBalance,
boolean add, int amount) {
for(String key:accountBalance.keySet()){
int currentBal = accountBalance.get(key);
if(add){
accountBalance.put(key,currentBal+amount*Constants.MULTIPLIER_ONE); // do lot of calculations
}else{
accountBalance.put(key,currentBal+amount*Constants.MULTIPLIER_NEGATIVE_ONE);// do a lot of calculations
}
}
}
}
请在我的示例中建议枚举会更好或者我目前使用常量的方法已经足够好?
最佳答案
在您的特定情况下,使用枚举是经典解决方案。
首先,让我们将您的常量
重写为枚举:
public enum Constants {
ACCOUNT,
EVENT_ITEM,
;
}
public enum Operation {
MULTIPLIER_ONE {
public int action(int value) {
return value;
}
},
MULTIPLIER_NEGATIVE_ONE {
public int action(int value) {
return value * (-1);
}
},
;
private Operation(int coef) {
this.coef = coef;
}
public abstract int action(int value);
}
现在不用写了:
if(Constants.ACCOUNT.equals(fileType)){
} else if(....)
您可以使用 switch/case
或更好地定义:define 方法(让我们将其称为 action()
到枚举中并从您的代码中调用它。参见示例在上面的 Operation
枚举中。在这种情况下,您的代码变得微不足道:不再有 if/else
或 switch 语句。一切都很简单。验证在编译时完成:您定义了 abstract枚举中的方法,如果不为其实现此方法,则无法向枚举添加另一个元素。使用 if/else
结构时不会发生这种情况,维护是程序员的责任。
我只知道枚举的一个限制:在注释中使用字符串常量。有很多带有字符串属性的注解。例如 XmlElement(name="foo")
。即使你定义枚举
enum FooBar {
foo, bar
}
你不能在注释中使用它:
@XmlElement(name=FooBar.foo) // is wrong because String type is required
@XmlElement(name=FooBar.foo.name()) // is wrong because annotations do not support method invocation
在所有其他情况下,我更喜欢枚举。
关于java - 枚举作为 Java 中常量的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24524371/
我不完全确定我理解 substitute 的作用,尽管我以前在它的代码中使用过。今天在shiny::exprToFunction中遇到了如下几行代码: function (expr, env = pa
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,因为
我最近发现了 crockford 的 Javascript supplant 函数。函数是这样的—— if (!String.prototype.supplant) { String.prot
在我工作的一些项目中,添加了一些具有这种语法的 block : var [code, name] = input.split("/"); console.log(code); console.log(
我对 JavaBeans 模式的憎恨就像一千个太阳的火焰一样燃烧。为什么? 冗长。现在是 2009 年。我不应该为一个属性写 7 LOC。如果他们有事件监听器,请捕获你的帽子。 没有类型安全的引用。没
是否有比 PHP 执行速度更快且具有相同功能集(例如对常见 RDBMS、Curl、Regex 等的支持)的替代品? 用 C 编写网站代码怎么样?效果如何?该平台是否独立并在每台服务器上运行? 最佳答案
我正在开始新项目。客户端界面基于 GWT(和 GXT),我没有说它是预先确定的。但是,我可以选择服务器端,这样我就可以玩得开心,并希望在这个过程中学到一些新东西。一些要求是: 与服务器的交换将通过使用
我目前使用 CentOS 5.6(Ghostscript 8 - ImageMagick-6.2.8) 我正在尝试将 pdf 的第一张图像转换为 jpg 文件。 我知道我当前的设置无法转换压缩的 pd
2021 年更新: 只使用 MathJax;您不应该再支持旧版本的 IE。 我想使用 MathJax 来显示 MathML 方程,但它在 IE 中的性能慢得令人无法接受(是的,我读过使用 Emulat
BinaryFormatter 序列化的 128³ 数组加倍,占用 50 MB 空间。序列化具有两个双字段的 128³ 结构数组需要 150 MB 和超过 20 秒的处理时间。 是否有快速简单的替代方
我发现 $.each 非常慢,如果包含大量各种 jQuery 效果,会给网页带来问题。 我想知道 $.each 是否有一个好的替代方案,例如: $('ul li').each(function() {
我正在编写一个Mac应用程序,它提供类似“测试”的功能。此应用程序(通过与服务器的连接)。基本上,该应用程序将为学生提供一个故事供阅读,然后是一系列问题(也来自服务器),用户可以(尝试)选择正确的答案
我喜欢 WPF,但我讨厌 XAML。 XAML 过于冗长,在 Microsoft 尝试对其进行扩展时出现语法问题(请参阅 StringFormat on Bindings),并且难以导航。 XAML
已结束。此问题正在寻求书籍、工具、软件库等的推荐。它不满足 Stack Overflow guidelines 。目前不接受答案。 我们不允许提出寻求书籍、工具、软件库等推荐的问题。您可以编辑问题,以
有没有类似 SoftwareFx 的 PowerGadgets 的产品?我正在查看支持自动刷新的 powershell 的仪表控件。 最佳答案 检查 ShowUI 模块。 http://showui.
我正在开发一个项目,其中页面需要能够根据服务器的状态保持更新。 我喜欢 websocket,因为它们为我提供了一种从服务器推送消息的方法,但可用性是一个问题。 我需要通用方法在网络服务器和浏览器客户端
我最近一直在使用 openX 自托管广告管理软件,但它太慢了。 目标:我需要能够展示一个广告,获得 10 次点击,然后停用该广告,并且每天都这样做。 问题:当我将 openX 设置为每天 10 次点击
就目前情况而言,这个问题不太适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、民意调查或扩展讨论。如果您觉得这个问题可以改进并可能重新开放,visit
我正在尝试实现一个简单的类,该类允许用户裁剪用于其个人资料图片的图像。这是一个 Java Web 应用程序。 我做了一些搜索,发现 java.awt 有一个 BufferedImage 类,这看起来(
只是一个关于 JQuery 的简单问题,我一直在使用phonegap 并使用 JQuery 制作了一些应用程序。其中一个运行速度非常慢,所以我一直在努力尽可能地精简它。 我一直在考虑的一个更改是用更小
我是一名优秀的程序员,十分优秀!