Sometimes there is situations where I need to take a value from a database lookup table similar to:
Id | Description
----------------
1 | descriptive text for 1
2 | descriptive text for 2
The Id vlaue is often stored in a variable:
private int DB_LookUp_Id = GetIdFromDB();
This DB_LookUp_Id value is then used to perform validation or other business logic like:
if (DB_LookUp_Id == 1)
return true
This code will break if the Id value changes from, say 1 to 3
What is a good way to eliminate this problem?
Thanks
Have a code-based key alongside the database ID that is static, we tend to use either Guids or enumerated values for this:
Then in code you could have:
Not sure if this is “best practice”, but it works for us. Database primary keys do not always need to be known or used by the application, though most of the time they are.
Alternatively, if it’s all just text, ship it all into a resource file. This gives you localisation, compile-time benefits, and performance benefits. To the detriment of database access to resource strings (pretty much no access), and ability to release new strings without re-compilation.