为什么使用枚举而不是常量?在软件设计和可读性方面哪个更好 [英] Why use Enums instead of Constants? Which is better in terms of software design and readability

查看:14
本文介绍了为什么使用枚举而不是常量?在软件设计和可读性方面哪个更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,其中我有 玩家类型 ARCHERWARRIORsorcerer.
我应该在 Player 类中为玩家类型使用什么?
常量 final static String 变量还是 Enum?为什么?
请帮忙说明原因.

I have a scenario in which I have Player types ARCHER,WARRIOR, and sorcerer.
What should I use in Player class for a player type?
Constant final static String variable or an Enum? and Why?
Please help with reasons.

推荐答案

假设您使用常量字符串(或 int 值 - 它们也是如此):

Suppose you use constant strings (or int values - the same goes for them):

// Constants for player types
public static final String ARCHER = "Archer";
public static final String WARRIOR = "Warrior";

// Constants for genders
public static final String MALE = "Male";
public static final String FEMALE = "Female";

然后你最终不会真正知道你的数据类型——导致可能不正确的代码:

then you end up not really knowing the type of your data - leading to potentially incorrect code:

String playerType = Constants.MALE;

如果你使用枚举,结果会是:

If you use enums, that would end up as:

// Compile-time error - incompatible types!
PlayerType playerType = Gender.MALE;

同样,枚举给出一组受限的值:

Likewise, enums give a restricted set of values:

String playerType = "Fred"; // Hang on, that's not one we know about...

对比

PlayerType playerType = "Fred"; // Nope, that doesn't work. Bang!

此外,Java 中的枚举可以有更多与之相关的信息,也可以有行为.全面好多了.

Additionally, enums in Java can have more information associated with them, and can also have behaviour. Much better all round.

这篇关于为什么使用枚举而不是常量?在软件设计和可读性方面哪个更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆