views:

74

answers:

3

Lets say i got a enum table like this:

id  name    desc
0   Normal  Normal shipping
1   Fragile Fragile, handle with care

and i got some business rule on an order

double ShippingPrice(Product p)
{
  if (p.ShippingType == 1) // Fragile
     return GetFragileShippingPrice(p);
  else
     return GetNormalShippingPrice(p);
}

Maybe not the best example. But the point is, how do you make the "p.ShippingType == 1" part readable. When the next person comes along to maintain this code, he has to find the production database, and query tables for every business rule to understand what they do.

I've considerd just creating an enum in code just do duplicate the data in the database, but that don't seem like a good solution either.

A: 
enum ShippingType : int
{
  Normal = 0,
  Fragile = 1
}

double ShippingPrice(Product p)
{
  if (p.ShippingType == ShippingType.Fragile) // Fragile
     return GetFragileShippingPrice(p);
  else
     return GetNormalShippingPrice(p);
}

Then you would have the enum auto-generated (created by something like CodeSmith) from a table in your database.

s_hewitt
A: 

A lengthy discussion is here

RandomNoob
A: 

I don't think you'll get away with anything other than either manually editing your enum or creating it by using code generation. You can create it using t4 templates, from where you could fetch the information from your database, or some other means of generation.

In either case you would really want to have them available at compile-time for type safety and ease of use. Sure you can create dynamic enums as in the lengthy discussion link from bnkdev's post, but if you think about how they would be used you would be just as well off with a constant, which would defeat the purpose.

Runeborg