为什么使用枚举而不是常量?哪个在软件设计和可读性方面更好 [英] Why use Enums instead of Constants? Which is better in terms of software design and readability
问题描述
我有一个场景,我有玩家类型ARCHER,WARRIOR和巫师。我应该在玩家类中使用什么?类型或枚举的String变量?为什么枚举和为什么Constant Strings。请帮助解释原因。
I have a scenario in which I have Player types ARCHER,WARRIOR, and sorcerer. What should I use in player class? A String variable for type or a Enum? Why enum and why Constant Strings. 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...
vs
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屋!