Java 编码约定 - 命名枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3069743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:12:10  来源:igfitidea点击:

Coding Conventions - Naming Enums

javastandardscoding-style

提问by

Is there a convention for naming enumerations in Java?

Java 中是否有命名枚举的约定?

My preference is that an enum is a type. So, for instance, you have an enum

我的偏好是枚举是一种类型。因此,例如,您有一个枚举

Fruit{Apple,Orange,Banana,Pear, ... }

NetworkConnectionType{LAN,Data_3g,Data_4g, ... }

I am opposed to naming it:

我反对命名它:

FruitEnum
NetworkConnectionTypeEnum

I understand it is easy to pick off which files are enums, but then you would also have:

我知道很容易挑选出哪些文件是枚举,但是你也会有:

NetworkConnectionClass
FruitClass

Also, is there a good document describing the same for constants, where to declare them, etc.?

另外,是否有一个很好的文档来描述常量,在哪里声明它们等等?

采纳答案by DJClayworth

Enums are classes and should follow the conventions for classes. Instances of an enum are constants and should follow the conventions for constants. So

枚举是类,应该遵循类的约定。枚举的实例是常量,应该遵循常量的约定。所以

enum Fruit {APPLE, ORANGE, BANANA, PEAR};

There is no reason for writing FruitEnum any more than FruitClass. You are just wasting four (or five) characters that add no information.

没有理由编写 FruitEnum 和 FruitClass 一样。您只是在浪费四个(或五个)不添加任何信息的字符。

Java itself recommends this approach and it is used in their examples.

Java 本身推荐这种方法,并在他们的示例中使用

回答by Jim B

In our codebase; we typically declare enums in the class that they belong to.

在我们的代码库中;我们通常在它们所属的类中声明枚举。

So for your Fruit example, We would have a Fruit class, and inside that an Enum called Fruits.

因此,对于您的 Fruit 示例,我们将有一个 Fruit 类,并在其中包含一个名为 Fruits 的 Enum。

Referencing it in the code looks like this: Fruit.Fruits.Apple, Fruit.Fruits.Pear, etc.

在代码中引用它看起来像这样: Fruit.Fruits.Apple, Fruit.Fruits.Pear等。

Constants follow along the same line, where they either get defined in the class to which they're relevant (so something like Fruit.ORANGE_BUSHEL_SIZE); or if they apply system-wide (i.e. an equivalent "null value" for ints) in a class named "ConstantManager" (or equivalent; like ConstantManager.NULL_INT). (side note; all our constants are in upper case)

常量遵循同一条线,它们要么在与其相关的类中定义(例如Fruit.ORANGE_BUSHEL_SIZE);或者,如果它们在名为“ConstantManager”(或等效;如ConstantManager.NULL_INT)的类中应用系统范围(即 int 的等效“空值” )。(旁注;我们所有的常量都是大写的)

As always, your coding standards probably differ from mine; so YMMV.

与往常一样,您的编码标准可能与我的不同;所以YMMV。

回答by Bill the Lizard

They're still types, so I always use the same naming conventions I use for classes.

它们仍然是类型,所以我总是使用与类相同的命名约定。

I definitely would frown on putting "Class" or "Enum" in a name. If you have both a FruitClassand a FruitEnumthen something else is wrong and you need more descriptive names. I'm trying to think about the kind of code that would lead to needing both, and it seems like there should be a Fruitbase class with subtypes instead of an enum. (That's just my own speculation though, you may have a different situation than what I'm imagining.)

我绝对不会在名称中加入“Class”或“Enum”。如果您同时拥有 aFruitClass和 a,FruitEnum那么其他东西就错了,您需要更多描述性的名称。我正在尝试考虑哪种代码会导致两者都需要,而且似乎应该有一个Fruit带有子类型而不是枚举的基类。(不过,这只是我自己的猜测,您的情况可能与我想象的不同。)

The best reference that I can find for naming constants comes from the Variables tutorial:

我可以找到的命名常量的最佳参考来自变量教程

If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

如果您选择的名称仅包含一个单词,请用所有小写字母拼写该单词。如果它由多个单词组成,则将每个后续单词的第一个字母大写。名称 gearRatio 和 currentGear 是此约定的主要示例。如果您的变量存储一个常量值,例如 static final int NUM_GEARS = 6,则约定略有变化,将每个字母大写并用下划线字符分隔后续单词。按照惯例,下划线字符永远不会在其他地方使用。

回答by StaticNoiseLog

This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussionand MSDN Enumeration Type Naming Guidelines.

这可能不会让我结交很多新朋友,但应该补充一点,C# 人员有不同的准则:枚举实例是“Pascal case”(大写/小写混合)。请参阅stackoverflow 讨论MSDN 枚举类型命名指南

As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.

当我们与 C# 系统交换数据时,我很想完全复制它们的枚举,忽略 Java 的“常量具有大写名称”约定。考虑一下,我认为将枚举实例限制为大写没有多大价值。出于某些目的, .name() 是获取枚举常量的可读表示的方便快捷方式,混合大小写的名称看起来会更好。

So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.

所以,是的,我敢于质疑 Java 枚举命名约定的价值。“编程世界的另一半”确实使用了不同的风格这一事实让我认为怀疑我们自己的宗教是合理的。

回答by beosign

As already stated, enum instances should be uppercase according to the docs on the Oracle website (http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html).

如前所述,根据 Oracle 网站 ( http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html)上的文档,枚举实例应该是大写的。

However, while looking through a JavaEE7 tutorial on the Oracle website (http://www.oracle.com/technetwork/java/javaee/downloads/index.html), I stumbled across the "Duke's bookstore" tutorial and in a class (tutorial\examples\case-studies\dukes-bookstore\src\main\java\javaeetutorial\dukesbookstore\components\AreaComponent.java), I found the following enum definition:

但是,在浏览 Oracle 网站 ( http://www.oracle.com/technetwork/java/javaee/downloads/index.html)上的 JavaEE7 教程时,我偶然发现了“Duke's bookstore”教程和课程(tutorial\examples\case-studies\dukes-bookstore\src\main\java\javaeetutorial\dukesbookstore\components\AreaComponent.java),我找到了以下枚举定义:

private enum PropertyKeys {
    alt, coords, shape, targetImage;
}

According to the conventions, it should have looked like:

根据惯例,它应该是这样的:

public enum PropertyKeys {
    ALT("alt"), COORDS("coords"), SHAPE("shape"), TARGET_IMAGE("targetImage");

    private final String val;

    private PropertyKeys(String val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return val;
    }
}

So it seems even the guys at Oracle sometimes trade convention with convenience.

因此,似乎即使是 Oracle 的人有时也会为了方便而交换惯例。

回答by Damian kober

enum MyEnum {VALUE_1,VALUE_2}

is (approximately) like saying

是(大约)喜欢说

class MyEnum {

    public static final MyEnum VALUE_1 = new MyEnum("VALUE_1");
    public static final MyEnum VALUE_2 = new MyEnum("VALUE_2");

    private final name;

    private MyEnum(String name) {
        this.name = name;
    }

    public String name() { return this.name }
}

so I guess the all caps is strictly more correct, but still I use the class name convention since I hate all caps wherever

所以我想全大写更正确,但我仍然使用类名约定,因为我讨厌所有大写

回答by Xennex81

If I can add my $0.02, I prefer using PascalCase as enum values in C.

如果我可以加上 0.02 美元,我更喜欢使用 PascalCase 作为 C 中的枚举值。

In C, they are basically global, and PEER_CONNECTED gets really tiring as opposed to PeerConnected.

在 C 中,它们基本上是全局的,与 PeerConnected 相比,PEER_CONNECTED 变得非常累人。

Breath of fresh air.

呼吸新鲜空气。

Literally, it makes me breathe easier.

从字面上看,它让我呼吸更轻松。

In Java, it is possible to use raw enum names as long as you static import them from another class.

在 Java 中,只要您从另一个类静态导入它们,就可以使用原始枚举名称。

import static pkg.EnumClass.*;

Now, you can use the unqualified names, that you qualified in a different way already.

现在,您可以使用非限定名称,您已经以不同的方式限定了这些名称。

I am currently (thinking) about porting some C code to Java and currently 'torn' between choosing Java convention (which is more verbose, more lengthy, and more ugly) and my C style.

我目前(正在考虑)将一些 C 代码移植到 Java 并且目前在选择 Java 约定(更冗长、更冗长、更丑陋)和我的 C 风格之间“左右为难”。

PeerConnected would become PeerState.CONNECTED except in switch statements, where it is CONNECTED.

PeerConnected 将变为 PeerState.CONNECTED,除非在 switch 语句中,它是 CONNECTED。

Now there is much to say for the latter convention and it does look nice but certain "idiomatic phrases" such as if (s == PeerAvailable)become like if (s == PeerState.AVAILABLE)and nostalgically, this is a loss of meaning to me.

现在对于后一种约定有很多话要说,它确实看起来不错,但是某些“惯用语”,例如if (s == PeerAvailable)变得像if (s == PeerState.AVAILABLE)和怀旧,这对我来说失去了意义。

I think I still prefer the Java style because of clarity but I have a hard time looking at the screaming code.

我想我仍然更喜欢 Java 风格,因为清晰,但我很难看到尖叫的代码。

Now I realize PascalCase is already widely used in Java but very confusing it would not really be, just a tad out of place.

现在我意识到 PascalCase 已经在 J​​ava 中被广泛使用,但非常令人困惑,它实际上并不是,只是有点不合适。