Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I ever use Enums as discriminators?

Tags:

.net

oop

enums

When do Enumerations break down?


To support a new feature in an existing system, I was just considering implementing some form of discriminator to an entity table in my database schema.

In wanting to begin by doing the least thing that will work I first of all decided on an integer column and a C# enum at the business entity layer for the sake of readability. This would provide the poor-man's polymorphism that may eventually grow into an actual polymorphism and perhaps towards a Strategy pattern.

I decided to consult the blogosphere as I've never been entirely comfortable with using enums - I wondered, should I skip the enum and go straight for a struct or a class?:

First of all I found an assertion that 'Enums are Evil', but I felt this was an over-generalization which does not directly address my use-case.

If I do go for an enum then there's a good discussion of how I can extend my mileage by adding extra metadata to my enum.

Next, I came across Jimmy Bogard's discussions of Enumeration Classes and further discussed in 'Strategies and discriminators in NHibernate'

Should I skip the enums and go straight for Enumeration Classes? Or does anyone have any other suggestions for how to add a simple entity discriminator to my domain model.

Update:

I'd also add that both NHibernate and LINQ to SQL (and probably all other ORM-related data-access methods) make the use of enums very enticing as they let you map a discriminator column transparently in the mapping.

Would it be as easy to map an Enumeration Class?

Related questions:

  • /492096/persisting-data-suited-for-enums
  • /746812/best-practices-for-using-and-persisting-enums

Disclaimer:

Despite my careless use of the term entity (with a lower case 'e') I don't claim to be discussing DDD here...

like image 869
rohancragg Avatar asked Nov 30 '09 11:11

rohancragg


2 Answers

Today enums are evil, tomorrow OOP might be evil and AOP will be fine.

Just use the right tool for the job. Remember, Keep It Simple...

If the enum is just for the sake of telling the type of an object - don't bother, use it.

If it has some business logic in it, then it is probably another class.

like image 58
Dmytrii Nagirniak Avatar answered Oct 04 '22 19:10

Dmytrii Nagirniak


Those Enumeration Classes look neat, I've often looked jealously at Java's enums.

I think the usual rules apply: do the Simplest Thing That Could Possibly Work. If you find yourself with more than one switch on the enum, then that's a smell, and time to consider the pattern you've found.

Otherwise, why burden yourself with something you don't need?

like image 23
Jeremy McGee Avatar answered Oct 04 '22 18:10

Jeremy McGee