如何避免使用枚举?
直到在这里提出问题之前,我从未考虑过(枚举)是一件“坏事”。对于那些认为它们不是最佳实践的人来说,有哪些方法/模式可以避免在代码中使用它们?
编辑:
public Enum SomeStatus
Approved = 1
Denied = 2
Pending =3
end Enum
Until asking a question on here I never considered (enums) to be a "bad thing." For those out there that consider them not to be best practice, what are some approachs/patterns for avoiding their use in code?
Edit:
public Enum SomeStatus
Approved = 1
Denied = 2
Pending =3
end Enum
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Fowler 的重构中描述了枚举的问题,其中它被认为是 >代码气味。它与类型安全无关,而是强制您在代码中散布
switch
语句,从而违反了DRY 原则。状态模式是相同结构的更好模型,因为它允许您实现和改变相关逻辑到同一个班级的同一个状态。这也增加了内聚性并减少了类耦合。
The problem with enums is described in Fowler's Refactoring, where it is considered a code smell. It has nothing to do with type safety, but rather that it forces you to sprinkle
switch
statements all over your code, thus violating the DRY Principle.The State pattern is a better model of the same structure because it lets you implement and vary the logic related to the same state in the same class. This also increases cohesion and lessens class coupling.
我认为使用枚举是一件好事。它提供了强大的类型安全性。
它们有时有一些缺点,但这通常与事先不知道每种可能的选择的情况有关。如果您有一组固定的选项(例如您的示例),那么强类型枚举是一件好事,不应避免。
I think using an enum is a good thing. It provides strong type safety.
They have some disadvantages at times, but this is really typically related to situations where every possible option is not known in advance. If you have a fixed set of options, such as your example, then strong typed enums are a good thing, and should not be avoided.
我喜欢
海龟课程枚举。I like
turtlesclass enums.我喜欢使用枚举来为相关的值集添加易于使用和理解的名称。我只是不喜欢 C# 实现。使用示例枚举:
即使 17 超出范围,它也可以毫无抱怨地编译和运行。
Delphi 有更好的枚举(或者至少,它曾经是 - 我已经使用它很多年了)
I like enums for putting easy-to-use-and-understand names on related sets of values. I just don't like the c# implementation. Using your sample enum:
This compiles and runs without complaint, even though 17 is way out of bounds.
Delphi has better enums (or at least, it used to - its been years since I have used it)
枚举的要点是它仅在一个地方定义(数据库术语的规范化)。如果此枚举是您正在编写的类的合法一部分,则继续。
否则,特别是如果您发现自己多次声明它,请重新考虑您的枚举的用途。它实际上携带数据吗?是否有足够的值来考虑将可能性存储在数据库中?
The main point with enumeration is that it is defined in only one place (normalisation in database terms). If this enumeration is legitimately part of the class you are writing, then carry on.
Otherwise, particularly if you find yourself declaring it more than once, rethink what your enumeration is for. Is it actually carrying data? Will there be enough values to consider storing the possibilities in a database?