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.
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(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!");
}
本文介绍了.NET中枚举类型的使用规范,包括命名、文档注释及单元测试的重要性。重点讲解了如何通过固定枚举成员的数值来避免API变更引发的问题,并提供了具体的单元测试示例。
297

被折叠的 条评论
为什么被折叠?



