Best practices for using and persisting enums

sleske picture sleske · Apr 14, 2009 · Viewed 22.7k times · Source

I've seen several questions/discussions here about the best way to handle and persist enum-like values (e.g. Persisting data suited for enums , How to persist an enum using NHibernate ), and I'd like to ask what the general consenus is.

In particular:

  • How should these values be handled in the code?
  • How should they be persisted to a database (as text/as a number)?
  • What are the tradeoffs of different solutions?

Note: I moved the explanations originally included in this question to an answer.

Answer

Paul Sonier picture Paul Sonier · Apr 28, 2009

I agree with much of what you say. One thing I'd like to append, though, about the persistence of enums: I don't believe the generation of the enums at build time from the DB values is acceptable, but I also think that the runtime check is not a good solution. I'd define a third means: have a unit test which will check the values of the enum against the database. This prevents "casual" divergence, and avoids the overhead of checking the enums against the database every time the code is run.