简体   繁体   English

为什么Enum被认为比常量更安全?

[英]Why is an Enum considered more type-safe than constants?

In our example, we can choose to define an Enumerated Type that will restrict the possible assigned values (ie improved type-safety): 在我们的示例中,我们可以选择定义一个Enumerated Type,它将限制可能的赋值(即改进的类型安全性):

public class OfficePrinter {

public enum PrinterState { Ready, OutOfToner, Offline };
public static final PrinterState STATE = PrinterState.Ready;
}

static final char MY_A_CONST = 'a';

Imagine these two method signatures: 想象一下这两个方法签名:

void rawF(char someFlag);

void enumF(MyFlags someFlag);

The latter is more restrictive as only the valid values of MyFlags are allowed. 后者更具限制性,因为只允许MyFlags的有效值。 In the former case, any character could be passed - even if only the values defined in "constants" where used. 在前一种情况下,任何字符可以传递 - 即使只使用了“常量”中定义的值。

Happy coding. 快乐的编码。

You could pass MY_A_CONST to any method that takes a char. 您可以将MY_A_CONST传递给任何带char的方法。 You could also pass any other char to a method that takes a char. 您还可以将任何其他char传递给接受char的方法。

You could pass Ready, OutOfToner, Offline, and null to a method that takes a PrinterState. 您可以将Ready,OutOfToner,Offline和null传递给采用PrinterState的方法。

You get safety by being able to limit the total set of values that can be passed to a method (or assigned to a variable). 通过限制可以传递给方法(或分配给变量)的值的总值,可以获得安全性。

Using enum over constants helps with type safety because if a function takes an enum and you pass it anything but an enum, the compiler will complain. 在常量上使用enum有助于类型安全,因为如果函数采用枚举并且除了枚举之外都传递它,编译器会抱怨。 With constants, you're accepting a pretty large range of data, most of which are invalid. 对于常量,您接受的是大量数据,其中大部分都是无效的。

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

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