您的位置:首页 > 其它

Best Practices for .NET enums.

2012-02-03 10:45 351 查看
Naming
In .NET, enums should not have an "Enum" suffix.

Enum documentation
Enums should have an API comment according following pattern.
/// <summary>

/// <para>

/// Defines values that specify the possible ....

/// </para>

/// </summary>

Unit tests
In .NET internally, enums are normally nothing else than ints. Enum members get numerated ascending (0, 1, 2, 3...) according their appearance
in the enum.
This leads to a problem. If we do not exactly specify their values within the code, we will introduce breaking API changes as soon as we add new values somewhere in the middle of the enum because now, all following values get a different
number. This is a critical bug in case we store the enum values persistently, such as in a database or on hard-disk.

Example:
public enum Something

{

None = 0,

Any, // will have value 1

Other, // will have value 2

}

public enum Something

{

None = 0,

Any, // will have value 1

BreakingAPI, // will get value 2, breaks API!!!

Other, // will now have value 3, API broken!!!

}

So, to avoid such situation, as soon as enums members are defined, they are not allowed to change their values anymore for all time. To ensure that, we write unit tests that check for those values to be correct.

[TestMethod]

public void Test_Something_ValuesRemainStable()

{

Assert.AreEqual(3, Enum.GetValues(typeof(Something)).Length, "There have been enumeration values added or removed. This is a BREAKING API CHANGE! More unit tests are needed.");

Assert.AreEqual(0, (int)Something.None, "The value of the enumeration member has changed. This is a BREAKING API CHANGE!");

Assert.AreEqual(1, (int)Something.Any, "The value of the enumeration member has changed. This is a BREAKING API CHANGE!");

Assert.AreEqual(2, (int)Something.Other, "The value of the enumeration member has changed. This is a BREAKING API CHANGE!");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: