应该总是在Java中使用枚举而不是常量 [英] Should you always use enums instead of constants in Java

查看:353
本文介绍了应该总是在Java中使用枚举而不是常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java< 1.5中,常量将像这样实现

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;
    }
...

/ p>

and you would use it like this:

MyClass myClass = new MyClass(MyClass.VERTICAL);

现在,在1.5中,你应该使用枚举:

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;
    }
...

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;
    }
...

现在我可以再做一次: / p>

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?

更新

Vilx-第一个强调我觉得我失踪 - 该枚举应该是一个一流的公民。在java中,这意味着它在包中获取自己的文件 - 我们没有命名空间。我认为这将是一个有点重量,但实际上做了,它绝对是正确的。

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的回答很好,但它没有真正强调非 - 嵌套枚举。此外,对于1.4 - 在JDK中有很多使用整数的地方,我真的在寻找一种方法来演化这种代码。

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.

推荐答案

不知道Java,但在.NET中,良好的做法是将枚举与使用它们的类并行,即使它仅由一个类使用。也就是说,你可以这样写:

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
    {
    }
}


$ b b

因此,您可以使用:

Thus, you can use:

MyClass c = new MyClass(MyEnum.MyValue);

这篇关于应该总是在Java中使用枚举而不是常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆