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

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

问题描述

我正在查看由公司其他部门维护的一些 Java 代码,顺便提一下,一些前 C 和 C++ 开发人员.无处不在的一件事是使用静态整数常量,例如

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

除了缺少最终"限定符之外,我对这种代码有点困扰.我希望看到的,从学校主要接受 Java 培训,会更像

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?

它要好得多,因为它为您提供了类型安全性并且是自我记录的.对于整数常量,您必须查看 API 文档以找出哪些值是有效的,并且没有什么可以阻止您使用无效值(或者更糟的是,完全不相关的整数常量).使用枚举时,方法签名会直接告诉您哪些值是有效的(IDE 自动补全会起作用),并且不可能使用无效值.

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.

不幸的是,整数常量枚举"模式非常普遍,即使在 Java 标准 API(并从那里广泛复制)中也是如此,因为 Java 在 Java 5 之前没有枚举.

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天全站免登陆