且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

const int而不是枚举的列表

更新时间:2023-02-05 20:52:35

我认为这里有很多答案忽略枚举的语义的含义。

I think many of the answers here ignore the implications of the semantics of enums.


  • 您应该考虑在整个所有有效值(Ids)集合提前知道时使用枚举,并且足够小以在程序代码中声明。

  • You should consider using an enum when the entire set of all valid values (Ids) is known in advance, and is small enough to be declared in program code.

如果一组已知值是所有可能值的子集,则应考虑使用int,而代码只需要注意此子集。

You should consider using an int when the set of known values is a subset of all the possible values - and the code only needs to be aware of this subset.

关于重构 - 在时间和业务限制允许的情况下,***在新设计/实施对于以前的实施和风险在哪里被很好的理解。在利益低或风险高(或两者兼有)的情况下,***采取不伤害的位置而不是不断改进 。只有你能够判断哪种情况适用于你的情况。

With regards to refactoring - when time and business contraints allow, it's a good idea to clean code up when the new design/implementation has clear benefit over the previous implementation and where the risk is well understood. In situations where the benefit is low or the risk is high (or both) it may be better to take the position of "do no harm" rather than "continuously improve". Only you are in a position to judge which case applies to your situation.

顺便说一句,既不是枚举或常量ints是一个好主意,当ID表示外部存储(如数据库)中的记录的标识符时。在程序逻辑中对这样的ID进行硬编码通常是有风险的,因为这些值在不同环境(例如,测试,开发,生产等)中可能实际上是不同的。在这种情况下,在运行时加载值可能是更合适的解决方案。

By the way, a case where neither enums or constant ints are necessarily a good idea is when the IDs represent the identifiers of records in an external store (like a database). It's often risky to hardcode such IDs in the program logic, as these values may actually be different in different environments (eg. Test, Dev, Production, etc). In such cases, loading the values at runtime may be a more appropriate solution.