views:

207

answers:

3

Say you have a 'post' object in a typical blog scenario. A blog post can have different statuses like 'draft', 'published', 'approved', et cetera. What are the best ways to handle this, specifically regarding storing this data in the database in a meaningful way as well as in a meaningful way in code.

Generally I've seen these stored as an int associated with a row in the database (of the 'posts' table in this example). Sometimes there's a lookup table in the database to explain these statuses (i.e. status table with id=>1 name=>draft, etc.). Normally, I'd translate these into an enum in the Data Access Layer to have a more meaningful code representation and to avoid having 'magic numbers'.

However, this solution has a developer updating two different places (database and code) to add or change a status type.

What's a better way to do this? This seems to be a type of problem I've run into frequently but I've never seen a good way to handle it.

+2  A: 

I like setting a status_id and creating a lookup table with the statuses in it and a corrresponding enum as you suggested.

If my statuses are essentially immutable (e.g. state of a blog post, state of an order, etc.), I will create a unit test that determines if the number of enums I use matches the data in the lookup table - so if someone were to add a status to the database in the future it would fail the test, telling the developer to add to the enum.

John Rasch
+1  A: 

IMO, they should be only be in one place , if you are mapping draft to a enum DRAFT in code that probably means that you are adding behavior to draft in code , like if draft is editable for example and making decisions based on that . My approach here would be to move the behavior to database and add a column to db for that behavior ( like boolean column to say if its editable) and map it to status class instead of a enum. So if a new status is introduced it can just be added to db with corresponding behavior.

Surya
A: 

I agree with John Rasch's answer, but you maybe interested in a post on Codeproject that talks about dynamic generation of enums

Jhonny D. Cano -Leftware-