Enumerations: Why? When?

后端 未结 7 1097
梦如初夏
梦如初夏 2020-11-30 08:37

I am an almost-graduating computer science student, and throughout my coding career, I\'ve found very few instances where enumerations, except for canonical cases such as re

7条回答
  •  醉酒成梦
    2020-11-30 09:00

    Enumerations are perfect for representing the state/status of something. I often use enums such as:

    public enum PlayerState {
        WALKING, STANDING, JUMPING...
    }
    

    There's always a balance to be struck between enumerations and derived classes. To give a simple example of this, consider a Cat class. Cats have different levels of hostility. So, we could make derived classes HostileCat, FriendlyCat, etc. However, there are also different types of cats, Lions, Tigers, etc. Suddenly, we have a whole bunch of Cat Objects. So, an alternative solution is to provide a Hostility enumeration in the Cat class, which reduces the number of derived classes and overall complexity.

提交回复
热议问题