According to the Best Practices section of the MSDN documentation for the System.Enum class:
Do not define an enumeration value solely to mirror the state of the enumeration itself. For example, do not define an enumerated constant that merely marks the end of the enumeration. If you need to determine the last value of the enumeration, check for that value explicitly. In addition, you can perform a range check for the first and last enumerated constant if all values within the range are valid.
If I understand correctly, we shouldn't declare an enum as follows.
public enum DrawOrder
{
VeryBottom = 0,
Bottom = 1,
Middle = 2,
Top = 3,
Lowest = VeryBottom, //marks a position in the enum
Highest = Top, //marks a position in the enum
}
Why is this considered bad practice?
Because those values may change over time. Suppose you set a property to (using your example) DrawOrder.Highest
and store it in your database/document/other-data-sink.
Time passes.
Code Changes.
Your DrawOrder
enum has acquired a few more values and the value in your persisted data is now no longer equal to DrawOrder.Highest
. It's only equal to what ever DrawOrder.Highest
mapped to at the time the data was persisted.
Do you think that this situation might have the possibility of causing problems?
Because if you add VeryTop = 4
to the enumeration, you have to remember to update Highest
.
If you fail to do so, all hell breaks loose. It's surprisingly easy to forget about that after some time (a few months) has passed.
I'm not sure I agree that it's bad practice; it depends.
Steve McConnell's Code Complete uses this construct. (This book is starting to show its age with the languages it uses, so this technique may have been good practice then.)
The downside is that there's an extra thing to remember to do if you update the enumeration list: update the value of Highest
and/or Lowest
, if needed. If you forget, you'll introduce bugs.
The upside is that the code you write for loops is faster and self-documenting.
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