How do you write code whose logic is protected against future additional enumerations?

后端 未结 10 1556
旧巷少年郎
旧巷少年郎 2021-02-05 08:01

I\'m having a hard time describing this problem. Maybe that\'s why I\'m having a hard time finding a good solution (the words just aren\'t cooperating). Let me explain via cod

10条回答
  •  醉话见心
    2021-02-05 08:45

    If I understood your question correctly, the most common practice is to throw an NotSupportedException or NotImplementedException.

    switch (fruit.Kind) {
    case Fruit.Apple:
        Bite(fruit);
        break;
    case Fruit.Banana:
        FeedToMonkey(fruit);
        break;
    default: throw new NotSupportedException("Unknown fruit.");
    }
    

    As for adding new enum values which would break existing if-not-is logic, I believe using enum is a poor choice in this case. Your items clearly have a distinctively different behavior, they're not like e.g. colors. Perhaps it is best to make the options responsible for deciding how they should be treated. Then you should replace enums with polymorphism.

提交回复
热议问题