在“验证”中使用异常是否更好?类或返回状态代码?
假设我正在创建一个类来验证数字,例如美国的“社会保障”(仅作为基于国家/地区的 ID 的示例)。有一些规则可以验证来自网站 html 表单输入的数字。
我正在考虑用 Python 创建一个简单的类和一个公共 validate 方法。这个validate
简单地返回True
或False
。此方法将调用其他小型私有方法(例如,如果存在不同的规则,则调用第一个“x”数字),每个方法也返回 True
或 False
。
因为这非常简单,所以我考虑仅使用布尔状态代码(如果它有效或无效,不需要关于错误的有意义的消息)。
我一直在阅读一些有关使用异常的文章,我想了解您对我的情况的看法:使用异常会是一个好主意吗?
Suppose I'm creating a class to validate a number, like "Social Security" in US (just as an example of a country-based id). There are some rules to validate this number that comes from an input in a html form in a website.
I thinking about creating a simple class in Python, and a public validate
method. This validate
returns True
or False
, simply. This method will call other small private methods (like for the first 'x' numbers if there is a different rule), each one returning True
or False
as well.
Since this is really simple, I'm thinking of using boolean status codes only (if it's valid or not, don't need meaningful messages about what is wrong).
I've been reading some articles about using exceptions, and I would like to know your opinion in my situation: would using exceptions would be a good idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个非常古老的问题,但由于唯一的答案 - IMO - 不适用于 Python,这是我的看法。
Python 中的异常是许多刚接触该语言的程序员难以处理的问题。与其他语言相比,Python 在如何使用异常方面存在显着差异:事实上,Python 通常使用异常来进行流程控制。
典型的例子是 for 循环:你肯定会同意,耗尽迭代的循环并没有什么“独特的奇怪”(事实上,这就是所有循环所做的,除非被破坏) )...然而,Python 并没有提前检查是否还有值需要处理,而是继续尝试从可迭代对象中读取值,如果失败,则会出现
StopIterator
异常,该异常又被for
表达式捕获并使代码退出循环。此外,Python 中惯用的做法是采用 EAFP(请求宽恕比请求许可更容易 =
try- except
),而不是 LBYL(三步走之前先看 = <代码>如果不是 A、B 或 C 则)。在这方面,csj 的答案对于 C 或 Java 是正确的,但与 Python 无关(Python 的异常本质上很少是“例外”)。
不过,另一个需要考虑的因素是用户数据无效但无法对验证函数结果采取行动的情况:
return 语句
,无法处理False
值将导致您的无效数据沿着管道发送,引发
异常,未能捕获它会导致异常通过您的堆栈传播,最终导致您的代码停止。虽然第二个选项一开始可能看起来很可怕,但它仍然是正确的选择:如果数据无效,那么将其进一步传递就没有意义......它很可能会在以后引入难以跟踪的错误在流程中,您还将错过修复代码中错误的机会(未能对无效数据采取行动)。
再次。 使用异常是pythonic的做法(但它不适用于大多数其他语言),正如这个其他答案以及zen of python :
哈!
This is a very old question but since the only answer - IMO - is not applicable to Python, here comes my take on it.
Exceptions in Python is something many programmers new to the language have difficulties dealing with. Compared to other languages, Python differs significantly in how exceptions are used: in fact Python routinely uses exceptions for flow control.
The canonical example is the
for
loop: you will certainly agree that there is nothing "uniquely bizarre" about the loop exhausting its iterations (indeed that's what all loops do, unless broken)... yet rather than checking in advance if there are still values to process, Python keeps on trying reading values from the iterable, and failing that, rises theStopIterator
exception, which in turn is catch by thefor
expression and make the code exiting the loop.Furthermore, it is idiomatic in Python to go by the EAFP (it's Easier to Ask for Forgiveness than Permission =
try-except
) rather than LBYL (Look Before You Leap =if not A, B or C then
).In this regard, csj's answer is correct for C or Java but is irrelevant for Python (whose exceptions are seldom "exceptional" in nature).
Another factor to consider - though - is the scenario in which user data is invalid but you fail to act on the validation function outcome:
return statement
, failing to process theFalse
value will result in having your non-valid data sent down the pipeline,raise
an Exception, failing to catch it would result in the exception propagating through your stack eventually resulting in your code to halt.While the second option might seems scary at first, it is still the right road to take: if data is invalid, there is no sense in passing it further down the line... it will most probably introduce difficult-to-track bugs later on in the flow and you will have also missed the chance to fix a bug in your code (failing to act on non-valid data).
Again. Using exceptions is the pythonic way to do (but it does not apply to most other languages) as also stated in this other answer and in the zen of python:
HTH!
如果输入有效或无效,则仅返回布尔值。验证测试遇到无效值并没有什么异常。
If an input is either valid or not, then just return the boolean. There's nothing exceptional about a validation test encountering an invalid value.