I have seen a common design pattern where there will be a "lookup table" in the database like this:
Color
ColorId | ColorName |
---|---|
1 | Blue |
2 | Red |
3 | Green |
with a foreign key constraint on other tables, such as:
Item
ItemId | ColorId |
---|---|
101 | 2 |
(Item.ColorId
is constrained to Color.ColorId
)
In the code, there is a corresponding enumerated type, such as:
enum Color {
Blue = 1,
Red = 2,
Green = 3
}
The problem is that the foreign key constraint only protects against one kind of error. You won't be able to insert 4 as a ColorId
into the Item
table. But this does not protect against an error like:
having:
enum Color {
Blue = 1,
Green = 2,
Red = 3
}
where the enum does not correspond to the lookup table. So if you have business logic code like:
if (item.Color == Color.Green) ...
it could really be acting on Red, not Green items.
Is there any technique to protect against this type of error? I just encountered an error like that in my current work.