简体   繁体   English

编码约定 - 命名枚举

[英]Coding Conventions - Naming Enums

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.? 另外,是否有一个好的文档描述了常量,在哪里声明它们等等?

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. 没有理由比FruitClass更多地编写FruitEnum。 You are just wasting four (or five) characters that add no information. 你只是在浪费四个(或五个)字符而不添加任何信息。

Java itself recommends this approach and it is used in their examples . Java本身推荐这种方法,并在它们的示例中使用它。

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). 这可能不会让我成为很多新朋友,但应该补充一点,C#人有不同的准则:枚举实例是“Pascal case”(大小写混合)。 See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines . 请参阅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. 当我们与C#系统交换数据时,我很想完全复制它们的枚举,而忽略了Java的“常量具有大写名称”约定。 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. 出于某些目的,.name()是获取枚举常量的可读表示的便捷快捷方式,并且混合大小写的名称看起来更好。

So, yes, I dare question the value of the Java enum naming convention. 所以,是的,我敢于质疑Java枚举命名约定的价值。 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. “编程世界的另一半”确实使用了不同的风格这一事实让我觉得怀疑我们自己的宗教是合法的。

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教程时,我偶然发现了“杜克的书店”教程和课堂( 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. 因此,即便是甲骨文公司的人也有时会以方便的方式进行交易。

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 ); 常量沿着同一行,它们要么在它们相关的类中定义(所以类似于Fruit.ORANGE_BUSHEL_SIZE ); or if they apply system-wide (ie an equivalent "null value" for ints) in a class named "ConstantManager" (or equivalent; like ConstantManager.NULL_INT ). 或者它们是否在名为“ConstantManager”的类(或类似的;类似于ConstantManager.NULL_INT )中应用系统范围(即int的等效“null值”)。 (side note; all our constants are in upper case) (旁注;我们所有常量都是大写)

As always, your coding standards probably differ from mine; 与往常一样,您的编码标准可能与我的不同; so YMMV. 所以YMMV。

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. 我绝对不赞成将“Class”或“Enum”放在一个名字中。 If you have both a FruitClass and a FruitEnum then something else is wrong and you need more descriptive names. 如果你同时拥有FruitClassFruitEnum那么其他东西就错了,你需要更多的描述性名称。 I'm trying to think about the kind of code that would lead to needing both, and it seems like there should be a Fruit base class with subtypes instead of an enum. 我正在尝试考虑那些导致需要两者的代码,似乎应该有一个带有子类型而不是枚举的Fruit基类。 (That's just my own speculation though, you may have a different situation than what I'm imagining.) (这只是我自己的猜测,你可能会遇到与我想象的情况不同的情况。)

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. 名称gearRatio和currentGear是此约定的主要示例。 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. 如果变量存储常量值,例如static final int NUM_GEARS = 6,则约定会略有变化,将每个字母大写并用后缀字符分隔后续单词。 By convention, the underscore character is never used elsewhere. 按照惯例,下划线字符从未在别处使用过。

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 所以我猜全部大写是严格的更正确,但我仍然使用类名约定,因为我讨厌所有大写的地方

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中,它们基本上是全局的,并且PEER_CONNECTED变得非常累,而不是PeerConnected。

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已经在Java中被广泛使用,但是它实际上并不是很混乱,只是有点不合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM