Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are position markers, like first or last, in an Enumeration considered bad practice?

Tags:

c#

enumeration

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?

like image 755
Osiris Avatar asked Sep 14 '12 18:09

Osiris


3 Answers

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?

like image 144
Nicholas Carey Avatar answered Nov 14 '22 22:11

Nicholas Carey


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.

like image 32
Frédéric Hamidi Avatar answered Nov 14 '22 22:11

Frédéric Hamidi


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.

like image 44
John Avatar answered Nov 14 '22 21:11

John