【发布时间】:2008-12-14 22:44:44
【问题描述】:
在java
public class MyClass {
public static int VERTICAL = 0;
public static int HORIZONTAL = 1;
private int orientation;
public MyClass(int orientation) {
this.orientation = orientation;
}
...
你会这样使用它:
MyClass myClass = new MyClass(MyClass.VERTICAL);
现在,在 1.5 中,您显然应该使用枚举:
public class MyClass {
public static enum Orientation {
VERTICAL, HORIZONTAL;
}
private Orientation orientation;
public MyClass(Orientation orientation) {
this.orientation = orientation;
}
...
现在你可以这样使用它:
MyClass myClass = new MyClass(MyClass.Orientation.VERTICAL);
我觉得有点难看。现在我可以轻松添加几个静态变量了:
public class MyClass {
public static Orientation VERTICAL = Orientation.VERTICAL;
public static Orientation HORIZONTAL = Orientation.HORIZONTAL;
public static enum Orientation {
VERTICAL, HORIZONTAL;
}
private Orientation orientation;
public MyClass(Orientation orientation) {
this.orientation = orientation;
}
...
现在我可以再次这样做了:
MyClass myClass = new MyClass(MyClass.VERTICAL);
具有枚举的所有类型安全优点。
这是好的风格,坏的风格,还是两者都不是。你能想出更好的解决方案吗?
更新
Vilx- 是第一个强调我所缺少的东西的人——枚举应该是一等公民。在 java 中,这意味着它在包中拥有自己的文件——我们没有命名空间。本来以为会有点重量级的,但实际做了之后,感觉确实不错。
Yuval 的回答很好,但并没有真正强调非嵌套枚举。此外,至于 1.4 - JDK 中有很多地方使用整数,我真的在寻找一种方法来改进这种代码。
【问题讨论】:
-
在第一个代码块中,您的意思是给每个变量一个不同的值,对吧?
-
你真的需要 MyClass 类来做更多的事情,而不仅仅是不同的 Orientations 可以做的事情吗?
标签: java coding-style enums