编写程序有时会用到有序常量。一个常见的情况是对命令行参数进行处理,如下的代码片段:
public class A {
…….
private
static final int PARAM_1 = 0;
private
static final int PARAM_2 = 1;
private
static final int PARAM_3 = 2;
private
static final int PARAM_4 = 3;
private
static final int PARAMS_COUNT = 4;
…….
public
static void main(String[] args) {
if
(args.length != PARAMS_COUNT) {
System.out.println("Usage:
program <Param_1> <Param_2> <Param_3> <Param_3>
<Param_4>");
System.exit(1);
}
callFun1(args[PARAM_1],
args[PARAM_2]);
callFun2(args[PARAM_1],
args[PARAM_3], args[PARAM_4]);
}
}
PARAM_1到PARAM_4就是我这里说的有序产量,这样的常量通常被赋予一段顺序的值。但如果像上面这段代码的写法,将会在程序维护时带来一些小麻烦。比如增加一个新的产量PARAM_5,除了需要定义型的常量以外,还需要调整PARAMS_COUNT的值。如果需要在原序列中插入一个新的常量,那就更麻烦了,不仅需要调整PARAMS_COUNT的值,还需要调整插入位置之后的常量的值。如在上面的代码中插入一个常量PARAM_NEW到PARAM_3的位置:
…….
private
static final int PARAM_1 = 0;
private
static final int PARAM_2 = 1;
private
static final int PARAM_NEW = 2 // New Constant
private
static final int PARAM_3 = 3; // Need Changed
private
static final int PARAM_4 = 4;
// Need Changed
private
static final int PARAMS_COUNT = 5; // Need
Changed
…….
其实我们只需要引入一个静态变量就可以比较好的解决这个问题。下面是修改后的代码:
public class A {
…….
private
static int PARAM_INDEX = 0;
private
static final int PARAM_1 = PARAM_INDEX++;
private
static final int PARAM_2 = PARAM_INDEX++;
private
static final int PARAM_3 = PARAM_INDEX++;
private
static final int PARAM_4 = PARAM_INDEX++;
private
static final int PARAMS_COUNT = PARAM_INDEX;
…….
}
在新的代码中,我们引入了一个变量PARAM_INDEX,并赋予一个初始值(这里是零),借助于对这个变量,我们消除了硬编码常量的值带来的那些弊端。同样插入一个新的常量,现在我们只需要增加新的内容,而不需要改变原有的代码了。代码如下:
public class A {
…….
private
static int PARAM_INDEX = 0;
private
static final int PARAM_1 = PARAM_INDEX++;
private
static final int PARAM_2 = PARAM_INDEX++;
private
static final int PARAM_NEW = PARAM_INDEX++;
// New Constant
private
static final int PARAM_3 = PARAM_INDEX++;
private
static final int PARAM_4 = PARAM_INDEX++;
private
static final int PARAMS_COUNT = PARAM_INDEX;
…….
}
posted on 2007-04-10 17:19
Jini 阅读(1535)
评论(4) 编辑 收藏 所属分类:
JDK相关