This is probably a naive question but I'm trying to figure out the industry best practice for working with magic numbers and their corresponding display texts. For example, whether a transaction is debit or credit might be stored as a bit field in the database, but the true/false/0/1 need to be displayed as "Debit" or "Credit" etc. Typically, there would be an enum as well that needs to be kept in sync with the magic numbers and their meanings.
There are two specific cases that I'm trying to resolve -
We want to translate them to human readable text - UI needs to know that when it sees zero, it needs to display "Debit" etc.
We want to work with the magic numbers within the source code - Here we usually translate them as enums. Enums get rid of the magic numbers but are hardcoded so difficult to keep in sync with the database values.
In a moderately sized application we can end up with hundreds to thousands of such translations, for example -
Context - {Value, Translation}
TransactionType - {0, Debit}, {1, Credit}
FileType - {0, CSV}, {1, XML}, {2, Excel}
ItemType - {0, Manual}, {1, Automated}, {2, Writeoff}, {3, System}
Status - {0, Active}, {1, InActive}, {2, Pending}, {3, Delivered} etc etc
I can't figure out a solution that allows enums to be synced/loaded dynamically from the database AND allows translations of database values to texts without losing referential integrity.
I see the below options -
- Hardcoding in the UI (Views or via GetDisplayTextFor(int) methods etc).
- Some external Text/XML files.
- A database table with columns (Context, Value, Translation) - But now we've created new magic numbers in the "Context" column.
- Database tables for each set of such mappings with values as referencing foreign keys - This will allow referential integrity but will mean addition of potentially numerous tables.
What are the industry practices for this problem? Can enums be generated dynamically from the database and can they be converted to texts or should enums be avoided altogether for such cases? Any other standard solutions/patterns that solve at least as much of the problem as possible?