Inheritance vs enum properties in the domain model

后端 未结 6 1026
予麋鹿
予麋鹿 2020-12-13 09:07

I had a discussion at work regarding \"Inheritance in domain model is complicating developers life\". I\'m an OO programmer so I started to look for arguments that having in

6条回答
  •  Happy的楠姐
    2020-12-13 09:26

    Enums are good when:

    1. The set of values is fixed and never or very rarely changes.
    2. You want to be able to represent a union of values (i.e. combining flags).
    3. You don't need to attach other state to each value. (Java doesn't have this limitation.)

    If you could solve your problem with a number, an enum is likely a good fit and more type safe. If you need any more flexibility than the above, then enums are likely not the right answer. Using polymorphic classes, you can:

    1. Statically ensure that all type-specific behavior is handled. For example, if you need all animals to be able to Bark(), making Animal classes with an abstract Bark() method will let the compiler check for you that each subclass implements it. If you use an enum and a big switch, it won't ensure that you've handled every case.

    2. You can add new cases (types of animals in your example). This can be done across source files, and even across package boundaries. With an enum, once you've declared it, it's frozen. Open-ended extension is one of the primary strengths of OOP.

    It's important to note that your colleague's example is not in direct opposition to yours. If he wants an animal's type to be an exposed property (which is useful for some things), you can still do that without using an enum, using the type object pattern:

    public abstract class AnimalType {
        public static AnimalType Unknown { get; private set; }
        public static AnimalType Cat { get; private set; }
        public static AnimalType Dog { get; private set; }
    
        static AnimalType() {
            Unknown = new AnimalType("Unknown");
            Cat = new AnimalType("Cat");
            Dog = new AnimalType("Dog");
        }
    }
    
    public class Animal {
        public AnimalType Type { get; set; }
    }
    

    This gives you the convenience of an enum: you can do AnimalType.Cat and you can get the type of an animal. But it also gives you the flexibility of classes: you can add fields to AnimalType to store additional data with each type, add virtual methods, etc. More importantly, you can define new animal types by just creating new instances of AnimalType.

提交回复
热议问题