针对switch语句枚举编程,这是你的方式做? [英] Programming against an enum in a switch statement, is this your way to do?
问题描述
看代码片段:
这是对一个枚举编码时,我通常做的。我有一个InvalidOperationException一个缺省的逃逸(因为编码是对一个私有实例字段没有传入的参数我不使用的ArgumentException或其derivals之一)。
我在想,如果你的开发伙伴与此逃生记....
公共枚举DrivingState {中性,驱动器还编码,停车,逆向};
公共类MyHelper
{
私人DrivingState drivingState = DrivingState.Neutral;
公共无效的run()
{
开关(this.drivingState)
{
情况下DrivingState.Neutral:
DoNeutral();
中断;
情况下DrivingState.Drive:
DoDrive();
中断;
情况下DrivingState.Parking:
DoPark();
中断;
情况下DrivingState.Reverse:
DoReverse();
中断;
默认:
抛出新的InvalidOperationException异常(
的String.Format(CultureInfo.CurrentCulture,
Drivestate {0}未知状态,this.drivingState));
}
}
}
在代码审查,我遇到很多实现只有在默认逃生break语句。这可能是随着时间的推移一个问题....
由于默认情况下是无法验证的,我不喜欢这种方式。这导致减少覆盖单元测试,这虽然不一定是世界末日,惹恼强迫我。</ p>
我更喜欢简单的单元测试每一种情况下,并有一个额外的断言仅存在四种可能的情况。一旦有人添加了新的枚举值,单元测试将打破。
类似
[测试]
公共无效ShouldOnlyHaveFourStates()
{
Assert.That(Enum.GetValues(typeof运算(DrivingState))。长度== 4,更新单元测试新DrivingState !!!);
}
Look at the code snippet:
This is what I normally do when coding against an enum. I have a default escape with an InvalidOperationException (I do not use ArgumentException or one of its derivals because the coding is against a private instance field an not an incoming parameter).
I was wondering if you fellow developers are coding also with this escape in mind....
public enum DrivingState {Neutral, Drive, Parking, Reverse};
public class MyHelper
{
private DrivingState drivingState = DrivingState.Neutral;
public void Run()
{
switch (this.drivingState)
{
case DrivingState.Neutral:
DoNeutral();
break;
case DrivingState.Drive:
DoDrive();
break;
case DrivingState.Parking:
DoPark();
break;
case DrivingState.Reverse:
DoReverse();
break;
default:
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture,
"Drivestate {0} is an unknown state", this.drivingState));
}
}
}
In code reviews I encounter many implementations with only a break statement in the default escape. It could be an issue over time....
I don't like this approach because the default case is untestable. This leads to reduced coverage in your unit tests, which while isn't necessarily the end of the world, annoys obsessive-compulsive me.
I would prefer to simply unit test each case and have an additional assertion that there are only four possible cases. If anyone ever added new enum values, a unit test would break.
Something like
[Test]
public void ShouldOnlyHaveFourStates()
{
Assert.That(Enum.GetValues( typeof( DrivingState) ).Length == 4, "Update unit tests for your new DrivingState!!!");
}
这篇关于针对switch语句枚举编程,这是你的方式做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!