【发布时间】:2012-03-16 05:22:16
【问题描述】:
为了输入验证的目的编写返回未引发异常的方法是一种不好的做法吗?如果输入有效,Validate 方法将返回 null,或者如果输入实际提交,则返回将引发的异常。
public Exception Validate(object input)
{
if (!SomeParametersMatch(input))
return new SomeException("Message...");
if (!SomeOtherParametersMatch(input))
return new SomeOtherException("Another message...");
// More cases here...
return null;
}
这样,您可以使用相同的函数来验证输入、向用户显示响应以及在代码中引发异常:
public void Submit(object input)
{
Exception ex = Validate(input);
if (ex != null) throw ex;
// Do whatever action here...
}
例如,如果您使用函数来标记可单击的空格,则可以为每个空格调用Validate,如果返回值不为空,则将它们标记为有效。然后 Submit 仅在用户实际单击空间并最终确定选择时才被调用。当您需要确保输入将在您选择时有效时,这将消除代码重复。
我可以让 Validate 返回一个 void 并简单地抛出异常,但由于 catching thrown exceptions is the most part of exception throwing 和 Validate 将在比有效输入更多的无效输入上运行,看起来像浪费。如果 Validate 仅在用户实际提交数据时使用,那么使用 try/catch 块我不会有问题。但由于它被用于过滤呈现给用户的数据,因此在大多数情况下抛出异常,只是为了捕获和丢弃它,似乎非常浪费。
【问题讨论】:
-
// Do whatever action here...中的代码如果您需要在第一次抛出异常时抛出,则不会执行。 -
仅当输入无效时。如果有效,
Validate将返回 null,Submit函数将运行。 -
对我来说这看起来很奇怪;基本上,您似乎用
return替换了throw。这真的值得努力吗?缺点是你必须记得扔到外面Validate()。把Validate()扔进去可以帮助你,以防你忘记了。