看一下代码片段:
这是我在编写枚举时通常所做的事情.我有一个带有InvalidOperationException的默认转义(我不使用ArgumentException或它的一个派生,因为编码是针对私有实例字段而不是传入参数).
我想知道你们的开发人员是否也编写了这个逃避的想法....
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)); } } }
在代码审查中,我遇到了许多在默认转义中只有break语句的实现.这可能是一个问题随着时间的推移....
你的问题有点模糊,但据我所知,你问我们你的编码风格是否合适.我通常根据它的可读性来判断编码风格.
我读了一次代码,我明白了.所以,在我看来,你的代码是良好编码风格的一个例子.
有一个替代方案,就是使用与Java的枚举类似的东西.私有嵌套类型允许"更严格"的枚举,其中编译时唯一可用的"无效"值是null
.这是一个例子:
using System; public abstract class DrivingState { public static readonly DrivingState Neutral = new NeutralState(); public static readonly DrivingState Drive = new DriveState(); public static readonly DrivingState Parking = new ParkingState(); public static readonly DrivingState Reverse = new ReverseState(); // Only nested classes can derive from this private DrivingState() {} public abstract void Go(); private class NeutralState : DrivingState { public override void Go() { Console.WriteLine("Not going anywhere..."); } } private class DriveState : DrivingState { public override void Go() { Console.WriteLine("Cruising..."); } } private class ParkingState : DrivingState { public override void Go() { Console.WriteLine("Can't drive with the handbrake on..."); } } private class ReverseState : DrivingState { public override void Go() { Console.WriteLine("Watch out behind me!"); } } }
我不喜欢这种方法,因为默认情况是不可测试的.这导致你的单元测试的覆盖率降低,虽然不一定是世界的末日,但是使我厌倦了强迫症.
我宁愿简单地对每个案例进行单元测试,并且还有一个额外的断言,即只有四种可能的情况.如果有人添加了新的枚举值,单元测试就会中断.
就像是
[Test] public void ShouldOnlyHaveFourStates() { Assert.That(Enum.GetValues( typeof( DrivingState) ).Length == 4, "Update unit tests for your new DrivingState!!!"); }
(DrivingState)-1 code>传递给它进行测试.
问题在于它无法帮助您修复代码.当你需要添加一个新状态时,你会更新"四个状态"测试 - 但是现在你有许多方法可以默默地进行操作.投掷WTF?运行时异常可能更可取.