当变量(特别是方法参数)只能从一组可能的值中取出一个时,应该总是使用枚举。示例将是类型常量(合同状态:“永久”,“临时”,“学徒”)或标志(“立即执行”,“延迟执行”)。
如果使用枚举而不是整数(或字符串代码),则增加了编译时检查,避免传入无效常量的错误,并记录哪些值是合法使用的。
BTW,过度使用枚举可能意味着你的方法太多了(通常最好有几个单独的方法,而不是一个方法,需要几个标志,它修改它的作用),但如果你必须使用标志或类型代码,枚举是要走的路。
例如,哪个更好?
/** Counts number of foobangs.
* @param type Type of foobangs to count. Can be 1=green foobangs,
* 2=wrinkled foobangs, 3=sweet foobangs, 0=all types.
* @return number of foobangs of type
*/
public int countFoobangs(int type)
与
/** Types of foobangs. */
public enum FB_TYPE {
GREEN, WRINKLED, SWEET,
/** special type for all types combined */
ALL;
}
/** Counts number of foobangs.
* @param type Type of foobangs to count
* @return number of foobangs of type
*/
public int countFoobangs(FB_TYPE type)
一个方法调用:
int sweetFoobangCount = countFoobangs(3);
然后变成:
int sweetFoobangCount = countFoobangs(FB_TYPE.SWEET);
在第二个例子中,它立即清楚哪些类型是允许的,docs和实现不能失去同步,编译器可以强制这样做。
此外,一个无效的调用像
int sweetFoobangCount = countFoobangs(99);
不再可能。