Java的枚举与静态常量 [英] Java enumerations vs. static constants

查看:873
本文介绍了Java的枚举与静态常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看这是由该公司的其他部分,顺带一些前C和C ++开发者保持一些Java code。有一点是无处不在是使用静态整型常量,如

 类引擎{
    私有静态诠释ENGINE_IDLE = 0;
    私有静态诠释ENGINE_COLLECTING = 1;
    ...
}

另外一个缺少最终预选赛,我有点被这种code的困扰。我也喜欢看,主要是被训练有素的在Java中从学校,会是更喜欢

 类引擎{
    私人枚举国家{空闲,收集};
    ...
}

然而,争论让我失望。为什么,如果在所有比前者后者更好?


解决方案

  

为什么,如果在所有,是后者更好
  比前者?


这是要好得多,因为它可以让你输入的安全,是自我记录。随着整型常量,你看API文档,找出哪些值是有效的,并且使用无效值(或完全无关可能更糟,整型常量)没什么prevents你。随着枚举,方法签名直接告诉你什么值是有效的(IDE自动完成将工作),它是不可能使用一个无效的值。

的整数常量枚举图案是不幸很常见的,即使在Java标准API(并从那里广泛复制)因为Java没有枚举前的Java 5

I'm looking at some Java code that are maintained by other parts of the company, incidentally some former C and C++ devs. One thing that is ubiquitous is the use of static integer constants, such as

class Engine {
    private static int ENGINE_IDLE = 0;
    private static int ENGINE_COLLECTING = 1;
    ...
}

Besides a lacking 'final' qualifier, I'm a bit bothered by this kind of code. What I would have liked to see, being trained primarily in Java from school, would be something more like

class Engine {
    private enum State { Idle, Collecting };
    ...
}

However, the arguments fail me. Why, if at all, is the latter better than the former?

解决方案

Why, if at all, is the latter better than the former?

It is much better because it gives you type safety and is self-documenting. With integer constants, you have to look at the API doc to find out what values are valid, and nothing prevents you from using invalid values (or, perhaps worse, integer constants that are completely unrelated). With Enums, the method signature tells you directly what values are valid (IDE autocompletion will work) and it's impossible to use an invalid value.

The "integer constant enums" pattern is unfortunately very common, even in the Java Standard API (and widely copied from there) because Java did not have Enums prior to Java 5.

这篇关于Java的枚举与静态常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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