简体   繁体   English

validate方法应该抛出异常吗?

[英]Should a validate method throw an exception?

I've implemented a little validation library which is used like this: 我已经实现了一个小验证库,使用如下:

domain_object.validate()

# handle validation errors in some way ...
if domain_object.errors:
    for error in domain_object.errors:
        print(error)

validate() performs the checks and populates a list called errors . validate()执行检查并填充名为errors的列表。

I know from other validation libraries that they throw exception when validation is performed unsuccessfully. 我从其他验证库中知道,当验证执行失败时,它们会抛出异常。 Error messages would be passed as an exception property. 错误消息将作为异常属性传递。

What approach is better? 什么方法更好? Is it advantageous to throw validation exceptions? 抛出验证异常是否有利?

No, I wouldn't think that a validation method should throw an exception. 不,我不认为验证方法应该抛出异常。

That would create a bit of an anti-pattern, as the client code calling the method would reasonably expect an exception to be thrown, and would then need to catch the exception. 这会产生一些反模式,因为调用该方法的客户端代码会合理地期望抛出异常,然后需要捕获异常。 Since it's generally recommended that exceptions not be used for flow control, why not just return a value indicating whether validation was successful or not. 由于通常建议不将异常用于流控制,为什么不返回指示验证是否成功的值。 The client code could check the return value and proceed accordingly. 客户端代码可以检查返回值并相应地继续。

You essentially accomplish the same thing as you would by throwing an exception, but without the extra cost and poor semantics of actually throwing an exception. 你基本上可以通过抛出异常来完成同样的事情,但是没有实际抛出异常的额外成本和糟糕的语义。

Exceptions should be reserved for truly exceptional conditions, not normal operation of a program. 例外情况应该保留用于真正特殊的条件,而不是程序的正常运行。 Failing validation to me seems like it is a pretty normal condition, something to be expected during the day-to-day operation of an application. 对我的验证失败似乎是一个非常正常的条件,在应用程序的日常操作期间可以预期 It would be easily handled by the calling code, and normal operation would continue. 它可以通过调用代码轻松处理,并且正常操作将继续。 Generally, that's not the case with exceptions. 通常情况下,例外情况并非如此。

I argue for the exact opposite: In a validation layer you want to ensure that every validation error is handled. 我认为恰恰相反:在验证层中,您希望确保处理每个验证错误。 If you rely on return values, there might be a bug in the integration code (especially when you use the validators in a different environment). 如果依赖返回值,则集成代码中可能存在错误(尤其是在不同环境中使用验证程序时)。

Python exceptions will make that problem obvious. Python异常会使问题变得明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM