Kan*_*ane 29 c# validation guard-clause
人们采用什么方法(如果有的话)管理班级中的防护条款爆炸?例如:
public void SomeMethod<T>(string var1, IEnumerable<T> items, int count)
{
if (string.IsNullOrEmpty(var1))
{
throw new ArgumentNullException("var1");
}
if (items == null)
{
throw new ArgumentNullException("items");
}
if (count < 1)
{
throw new ArgumentOutOfRangeException("count");
}
... etc ....
}
Run Code Online (Sandbox Code Playgroud)
在我目前正在进行的项目中,有许多类在公共方法上具有类似的一组保护条款.
我知道.NET 4.0代码合同,但目前这不是我们团队的选择.
Dav*_*own 49
我见过很多项目都使用静态Guard类.
public static class Guard {
public static void ArgumentIsNotNull(object value, string argument) {
if (value == null)
throw new ArgumentNullException(argument);
}
}
Run Code Online (Sandbox Code Playgroud)
在我看来,它使代码更清晰.
Guard.ArgumentIsNotNull(arg1, "arg1");
Run Code Online (Sandbox Code Playgroud)