I have a group of values that represent a state (ON, OFF, READY, ...). These values also get stored in a DB as an int field, so I am wondering if best practices would say to make this an enum or just bunch of const int types on a class.
Enum seems like a natural fit for human reading/coding, but it seems like it hides the fact that it matters which integers the values map to (or else values retrieved from a DB will be instantiated to the incorrect state). Someone may come in later and add a new value to the enum or something and throw the whole thing off.
Which is the better approach?
I think enum
is still the best choice for readability. However, since its values get stored in the DB, you should specify the values explicitly:
enum State { On = 1, Off = 2, Ready = 3};
How is somebody adding a new enum value any different than a new constant int?
Remember, you can set an enum to a specific integer value.
Embrace readability!
As an added bonus, you can now use strong typing to prevent shenanigans like
Widget.state = 474;
Where 474 does not correspond to a state in your database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With