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

后端 未结 10 1557
旧巷少年郎
旧巷少年郎 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:51

    This is a valid concern, and comes up most often when you're writing code against enums that are defined outside of your control, and which may evolve independently of your code. I'm referring to enums defined by the operating system or your execution environment, such as .NET itself. .NET (policy) explicitly allows enums to be extended across revisions of referenced assemblies, and this is not considered a breaking change.

    One the the most common approaches is simply to write your code to throw an exception if it ever receives an enum it isn't prepared for. This is a simple solution, but it may be overkill depending on what you're using the enums for.

    If you're using the enum to decide which of a fixed set of operations to perform, you don't have much choice but to throw if you encounter an unexpected enum.

    However, if you're using the enum to decide if you should perform additional specialized operations on top of default behavior, then it's not necessarily the case that unexpected enums are the end of the world.

    It's a judgment call that only you can make in the context of what your doing and in the context of what the enum actually represents. If you can write default behavior that you have high confidence should be acceptable for all enum cases, then maybe you can decide to accept future enum extensions without having to rewrite your code. This judgment call also requires evaluating your level of faith that the owner of the enum will extend the enum appropriately by not throwing completely unrelated stuff into the enum that requires completely different handling.

提交回复
热议问题