Why use Enums instead of Constants? Which is better in terms of software design and readability

后端 未结 5 913
一个人的身影
一个人的身影 2020-11-28 04:21

I have a scenario in which I have Player types ARCHER,WARRIOR, and sorcerer.
What should I use in Player class fo

5条回答
  •  萌比男神i
    2020-11-28 04:49

    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!
    

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

提交回复
热议问题