Tim*_*ner 7 c# defensive-programming exception break switch-statement
在一个只抛出异常的情况下,将无法达到的break语句留下来,这是愚蠢的吗?如果逻辑发生变化,我的防守部分希望将其留在那里.我的另一部分不希望其他开发人员在我的代码上看到编译器警告("检测到无法访问的代码").
switch (someInt)
{
case 1:
// Do something
break;
case 2:
// Do something else
break;
case 3:
// Oh, we don't use threes here!
throw new Exception("Business rules say don't use 3 anymore");
break; // Unreachable...until the fickle business rules change...
default:
throw new Exception("Some default exception");
break; // Unreachable...until...well, you get the idea.
}
Run Code Online (Sandbox Code Playgroud)
该怎么办?
UPDATE
我看到一些回复说在以后删除抛出会导致编译器错误.但是,简单地删除(或评论)抛出后不会中断它会堆叠案例,这可能是非预期的行为.我不是说这是一个可能的情况,但是......好吧,防御性的编程是否只打击可能的场景?
我不会"隐藏"它switch.我会ArgumentExceptions尽快扔掉.这避免了副作用,也更加透明.
有人可能会在切换之前添加代码,但在某些时候使用someInt虽然它是3.
例如:
public void SomeMethod(int someInt)
{
if (someInt == 3)
throw new ArgumentException("someInt must not be 3", "someInt");
switch (someInt)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)