【发布时间】:2012-03-14 16:53:41
【问题描述】:
考虑一个我可能控制也可能不控制的工厂方法,作为Func<T>传递给另一个类:
// this.FactoryMethod is an external dependency passed into this class
// through constructor or property injection assume that it is not null
// but there is no guarantee that it will return a non-null reference.
Func<IModel> FactoryMethod;
public IModel GetPopulatedModel(int state, FileInfo someFile)
{
// Argument validation omitted for brevity...
// This operation could return null.
var model = this.FactoryMethod()
if (model == null)
{
throw new SomeException("Factory method failed to produce a value.");
}
// Safe to assign to properties at this point.
model.Priority = state;
model.File = someFile;
return model;
}
我想抛出一些表明操作失败的东西。
ArgumentNullException 会产生误导,因为这些参数没有任何问题:
空引用时抛出的异常(Visual 中的Nothing Basic) 被传递给一个不接受它作为有效的方法 论据。
InvalidOperationException 似乎不太准确:
方法调用无效时抛出的异常 对象的当前状态。
将局部变量视为the object's current state 的一部分似乎很奇怪。
抛出什么是好的异常?我很惊讶System 中没有OperationFailedException。我应该编写自己的异常,还是有一个好的异常?
【问题讨论】:
-
空对象模式在这里也可能有用(但只有在广泛了解该工厂的使用情况下才适用)——这不是解决方案,而是需要考虑的其他问题。
-
对,但
Func<T>中没有任何内容可以保证这一点,所以我无法使用内置委托,我必须构建自己的类或委托类型,我'想避免。 -
如果我返回了一个实现空对象模式的对象,我仍然需要证明
model中的引用不为空。我想我可以使用struct来实现该模式。但随后我将不得不针对该结构而不是IModel接口进行编程。