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.
I like setting a
status_idand 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.