不属于java常量,应该总是在Java中使用枚举而不是常量

In java <1.5, constants would be implemented like this

public class MyClass {

public static int VERTICAL = 0;

public static int HORIZONTAL = 1;

private int orientation;

public MyClass(int orientation) {

this.orientation = orientation;

}

...

and you would use it like this:

MyClass myClass = new MyClass(MyClass.VERTICAL);

Now, in 1.5 obviously you should be using enums:

public class MyClass {

public static enum Orientation {

VERTICAL, HORIZONTAL;

}

private Orientation orientation;

public MyClass(Orientation orientation) {

this.orientation = orientation;

}

...

and now you would use it like this:

MyClass myClass = new MyClass(MyClass.Orientation.VERTICAL);

Which I find slightly ugly. Now I could easily add a couple of static variables:

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;

}

...

And now I can do this again:

MyClass myClass = new MyClass(MyClass.VERTICAL);

With all the type-safe goodness of enums.

Is this good style, bad style or neither. Can you think of a better solution?

Update

Vilx- was the first one to highlight what I feel I was missing - that the enum should be a first-class citizen. In java this means it gets its own file in the package - we don't have namespaces. I had thought this would be a bit heavyweight, but having actually done it, it definitely feels right.

Yuval's answer is fine, but it didn't really emphasise the non-nested enum. Also, as for 1.4 - there are plenty of places in the JDK that use integers, and I was really looking for a way to evolve that sort of code.

解决方案

Don't know about Java, but in .NET the good practice is to put enums in parallel to the class that uses them, even if it is used by one class alone. That is, you would write:

namespace Whatever

{

enum MyEnum

{

}

class MyClass

{

}

}

Thus, you can use:

MyClass c = new MyClass(MyEnum.MyValue);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值