如何避免使用枚举?

发布于 2024-08-21 19:43:05 字数 300 浏览 3 评论 0原文

直到在这里提出问题之前,我从未考虑过(枚举)是一件“坏事”。对于那些认为它们不是最佳实践的人来说,有哪些方法/模式可以避免在代码中使用它们?

编辑:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

悲喜皆因你 2024-08-28 19:43:05

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.

仙女山的月亮 2024-08-28 19:43:05

我认为使用枚举是一件好事。它提供了强大的类型安全性。

它们有时有一些缺点,但这通常与事先不知道每种可能的选择的情况有关。如果您有一组固定的选项(例如您的示例),那么强类型枚举是一件好事,不应避免。

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.

病毒体 2024-08-28 19:43:05

我喜欢海龟 课程枚举

I like turtles class enums.

猫烠⑼条掵仅有一顆心 2024-08-28 19:43:05

我喜欢使用枚举来为相关的值集添加易于使用和理解的名称。我只是不喜欢 C# 实现。使用示例枚举:

SomeStatus status = 17;

即使 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:

SomeStatus status = 17;

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)

┾廆蒐ゝ 2024-08-28 19:43:05

枚举的要点是它仅在一个地方定义(数据库术语的规范化)。如果此枚举是您正在编写的类的合法一部分,则继续。

否则,特别是如果您发现自己多次声明它,请重新考虑您的枚举的用途。它实际上携带数据吗?是否有足够的值来考虑将可能性存储在数据库中?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文