开发者

How to avoid using Enums?

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 ap开发者_运维百科proachs/patterns for avoiding their use in code?

Edit:

public Enum SomeStatus
 Approved = 1
 Denied = 2
 Pending =3
end Enum


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 turtles class enums.


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)


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜