java 在 Validate() 方法上抛出异常还是返回 bool 值更好?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5230978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:06:09  来源:igfitidea点击:

Is it a good practice to throw an exception on Validate() methods or better to return bool value?

c#javaexceptionvalidation

提问by pencilCake

Is it recommended or not to throw exceptions from Validation methods like:

是否建议或不从 Validation 方法中抛出异常,例如:

ValidateDates();
ValidateCargoDetails();

Apart from this : Is there a robust validation design pattern often used?

除此之外:是否经常使用健壮的验证设计模式?

回答by Andrew

I would suggest returning a ValidationResult object containing ValidationFailures. You should never use exceptions as part of your logical coding. Exceptions are for exceptions

我建议返回一个包含 ValidationFailures 的 ValidationResult 对象。您永远不应该将异常用作逻辑编码的一部分。例外是为了例外

回答by Adeel Ansari

I usually use visitor patternfor validating input; accumulating all the errors into a list or something to show the user. The logic goes like, checking the list for validation errors, if found, inform the user, otherwise good to go.

我通常visitor pattern用于验证输入;将所有错误累积到列表或其他内容中以显示给用户。逻辑是这样的,检查列表中的验证错误,如果发现,通知用户,否则很好。

IMO, validation errors are not something exceptional, hence it should not be dealt like one.

IMO,验证错误并不是什么特殊情况,因此不应像对待错误那样处理。

回答by bytedev

I would say it all depends on what/how you are doing the validation. But at the end of the day a developer can always choose to ignore a returned result (this is the problem with them), they can't ignore an exception without writing explicit code to do so.

我会说这完全取决于您进行验证的内容/方式。但是在一天结束时,开发人员总是可以选择忽略返回的结果(这是他们的问题),他们不能在不编写显式代码的情况下忽略异常。

回答by Peter Lawrey

Alot depends on how exceptional validation failures are are how critical it is to be correct.

在很大程度上取决于异常验证失败的正确性有多重要。

If your validation failures are rare and severe or fatal when they occur, I would use Exceptions or even AssertionErrors. Most parsers use Exceptions and these indicate it is not possible to continue processing.

如果您的验证失败发生时罕见且严重或致命,我会使用异常甚至断言错误。大多数解析器使用异常,这些表示无法继续处理。

If your validation failure are expected as under normal operations and do not indicate you cannot continue processing, I would suggest using a visitor pattern or return a List of issues (which can be empty)

如果您的验证失败在正常操作下预期失败并且不表明您无法继续处理,我建议使用访问者模式或返回问题列表(可以为空)

回答by Aliostad

Throwing exception must notbe used to control the flow of the application. As the name implies, it happens in exceptionalcases while validation could commonly fail. They are also expensiveand impact the performance.

不得使用抛出异常来控制应用程序的流程。顾名思义,它发生在特殊情况下,而验证通常会失败。它们也很昂贵并且会影响性​​能。

I would go with returning a boolean plus a string for reason.

我会返回一个布尔值和一个字符串 for reason

回答by ComeIn

Users entering invalid data is the very definition of an exception. When writing business requirements for a solution you always write the non-error paths as the main flow and error paths as exceptional paths. Using exceptions for validation is perfectly acceptable. Validating with exceptions also allows you to prioritise the order in how they are handled and to handle the error differently depending on what level you are at in the architecture stack (a string describing the error is of little use at the Data Access Layer).

用户输入无效数据就是异常的定义。在为解决方案编写业务需求时,您始终将非错误路径编写为主要流程,将错误路径编写为异常路径。使用异常进行验证是完全可以接受的。使用异常验证还允许您按处理顺序排列优先顺序,并根据您在架构堆栈中的级别(描述错误的字符串在数据访问层几乎没有用)以不同的方式处理错误。

回答by Dirk Boer

To be honest I'm quite on the fence on all of this. Sometimes I'm also building a visitor pattern, but it really feels I'm just re-implementing Exceptions.

老实说,我对所有这些都持观望态度。有时我也在构建一个访问者模式,但我真的觉得我只是在重新实现异常。

What I definitely don't like about the visitor pattern is that if your six levels deep and you notice that you need to break off you haveto check the result at every level above.

我绝对不喜欢访问者模式的一点是,如果您的六个级别很深,并且您注意到需要中断,必须检查以上每个级别的结果。

It means a lot of boilerplate code that actually can introduce bugs.

这意味着很多样板代码实际上可能会引入错误。

ExampleWhat if you checked A- it doesn not validate, but the code continues checking Bthat actually depends on a proper initialized A? In complicated validation logic this can happens on a lot of different paths. It is error prone.

示例如果您检查A- 它不会验证,但代码会继续检查B实际上取决于正确初始化的A? 在复杂的验证逻辑中,这可能发生在许多不同的路径上。它很容易出错。

On the other hand I used (custom) ValidationExceptionsand haven't come across any significant problems. You hit something that does not validate and you are ensured that all the other validation logic will be skipped. This is a big win for simplicity of code.

另一方面,我使用(自定义)ValidationExceptions并且没有遇到任何重大问题。您遇到了未验证的内容,并确保将跳过所有其他验证逻辑。这是代码简单性的一大胜利。

"Throwing exception must not be used to control the flow of the application."- for 99% of the other cases I would agree, but hanging on to this for validation logic seems to me based on dogma, not on pragmatism.

“不得使用抛出异常来控制应用程序的流程。” - 对于 99% 的其他情况,我会同意,但在我看来,为了验证逻辑而坚持这一点是基于教条,而不是实用主义。

About performace:Performance reasons are 99% not a concern in validation logic for user input, as this is almost never is done in tight loops.

关于性能:在用户输入的验证逻辑中,性能原因 99% 不是问题,因为这几乎从未在紧密循环中完成。

Summary:I recommend ignoring the "Exceptions are for Exceptional things"dogma, create (custom!) Exceptions that you throw and catch on the top level and see if it works for you. For me it does.

总结:我建议忽略“例外是为了特殊事物”的教条,创建(自定义!)在顶层抛出和捕获的异常,看看它是否适合你。对我来说确实如此。

回答by Betlista

I just wanted to bring this into the picture, answer of RADZSERG to the blog: Why throwing exceptions is better than returning error codes.

我只是想把这个带入图片,RADZSERG 对博客的回答:Why throwing exceptions is better thanreturns error codes

In short - we do not need to limit ourselves to use boolean as a return type...

简而言之 - 我们不需要限制自己使用布尔值作为返回类型......

I'm not telling that we should use or not to use Exception

but as for that specific article – you build bad code at the beginning then tries to make it better. Build good code at the beginning and the explain why it's better when we use exception. Here's my example

class TooManyLoginAttempts extends ValidationError{}

if ($hasTooManyLoginAttempts) {
    return new TooManyLoginAttempts()
}
...
$validationResult = $this->validate();
if ($validationResult instanceof ValidationError) {
    $this->errorLogger->log($validationResult->getMessage());
}

it also solves all described problems
– no magic numbers
– we're solving the problem of having the error code across our entire application
– my code is much shorter and also follows open-close principle

我不是在告诉我们应该使用还是不使用 Exception

但至于那篇特定的文章——你在开始时构建了糟糕的代码,然后试图让它变得更好。在开始时构建好的代码并解释为什么当我们使用异常时它会更好。这是我的例子

class TooManyLoginAttempts extends ValidationError{}

if ($hasTooManyLoginAttempts) {
    return new TooManyLoginAttempts()
}
...
$validationResult = $this->validate();
if ($validationResult instanceof ValidationError) {
    $this->errorLogger->log($validationResult->getMessage());
}

它还解决了所有描述的问题
——没有神奇的数字
——我们正在解决在整个应用程序中都有错误代码的问题
——我的代码更短,也遵循开闭原则

I came here from: Is it a good practice to throw an exception on Validate() methods or better to return bool value?which is locked.

我来自:在 Validate() 方法上抛出异常还是返回 bool 值更好?这是锁定的。