为什么 Enum 被认为比常量更类型安全?
在我们的示例中,我们可以选择定义一个枚举类型来限制可能的分配值(即改进的类型安全性):
public class OfficePrinter {
public enum PrinterState { Ready, OutOfToner, Offline };
public static final PrinterState STATE = PrinterState.Ready;
}
static final char MY_A_CONST = 'a';
In our example, we can choose to define an Enumerated Type that will restrict the possible assigned values (i.e. improved type-safety):
public class OfficePrinter {
public enum PrinterState { Ready, OutOfToner, Offline };
public static final PrinterState STATE = PrinterState.Ready;
}
static final char MY_A_CONST = 'a';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
想象一下这两个方法签名:
后者更具限制性,因为只允许
MyFlags
的有效值。在前一种情况下,可以传递任何字符 - 即使仅使用“常量”中定义的值。快乐编码。
Imagine these two method signatures:
The latter is more restrictive as only the valid values of
MyFlags
are allowed. In the former case, any character could be passed - even if only the values defined in "constants" where used.Happy coding.
在常量上使用
enum
有助于类型安全,因为如果一个函数采用枚举并且您向它传递除枚举之外的任何内容,编译器会抱怨。使用常量,您将接受相当大范围的数据,其中大部分都是无效的。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. With constants, you're accepting a pretty large range of data, most of which are invalid.您可以将 MY_A_CONST 传递给任何采用字符的方法。您还可以将任何其他字符传递给采用字符的方法。
您可以将 Ready、OutOfToner、Offline 和 null 传递给采用 PrinterState 的方法。
通过限制可以传递给方法(或分配给变量)的总值集,您可以获得安全性。
You could pass MY_A_CONST to any method that takes a char. You could also pass any other char to a method that takes a char.
You could pass Ready, OutOfToner, Offline, and null to a method that takes a 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).