重构保护条款 [英] Refactoring Guard Clauses
本文介绍了重构保护条款的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么样的方法做的人拿(如果有的话)在你的类管理后卫条款爆炸?例如:
What approaches do people take (if any) in managing guard clause explosion in your classes? For example:
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 ....
}
在我目前的工作在那里的项目有很多类,对公共方法类似组保护条款。
In the project that I am currently working on there are many classes that have a similar set of guard clauses on the public methods.
我知道了.NET 4.0代码契约的但是这不是我们球队目前的一个选项。
I am aware of the .NET 4.0 Code Contracts however this is not an option for our team at the moment.
推荐答案
很多项目是我见过使用静态卫队
类。
A lot of projects that I've seen use a static Guard
class.
public static class Guard {
public static void ArgumentIsNotNull(object value, string argument) {
if (value == null)
throw new ArgumentNullException(argument);
}
}
这使得代码变得更干净,在我看来,
It makes the code a lot cleaner, in my opinion.
Guard.ArgumentIsNotNull(arg1, "arg1");
这篇关于重构保护条款的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文