Achilles
Achilles

Reputation: 11299

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 approachs/patterns for avoiding their use in code?

Edit:

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

Upvotes: 16

Views: 12415

Answers (5)

Mark Seemann
Mark Seemann

Reputation: 233150

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.

Upvotes: 34

Arnis Lapsa
Arnis Lapsa

Reputation: 47587

I like turtles class enums.

Upvotes: 9

Phil H
Phil H

Reputation: 20141

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?

Upvotes: 2

Ray
Ray

Reputation: 21905

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)

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564413

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.

Upvotes: 13

Related Questions