Microsoft 代码契约是否不适合验证用户输入?

发布于 2024-09-17 06:40:11 字数 73 浏览 4 评论 0原文

我在 SO 的其他地方看到过它,虽然企业库验证应用程序块旨在验证用户输入,但代码契约旨在防止程序员错误。你会支持这个意见吗?为什么?

I've seen it written elsewhere on SO that while the Enterprise Library Validation Application Block is geared towards validating user inputs, Code Contracts are meant to prevent programmer errors. Would you support this opinion? Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

风和你 2024-09-24 06:40:11

是的。

代码合约旨在保持严格的编程接口,只有开发人员才能正确或错误;用户不应该真正搞砸这个。

验证是为了验证数据;例如,验证数据不为空,或者与正则表达式匹配。

Yes.

Code contracts are meant to keep a strict programming interface, which only a developer can get right or wrong; a user shouldn't really be able to mess this up.

Validation is meant to validate the data; e.g. verifying data isn't null, or matches a regex.

心是晴朗的。 2024-09-24 06:40:11

代码契约在被违反时会抛出异常。无效的用户输入不是异常情况,因此验证函数通常不应引发异常。这就是为什么像 TryParse 这样的方法被添加到框架中(原始框架没有它们,并且由于所有可能的异常而使验证变得麻烦)。

Code contracts throw exceptions when they are violated. Invalid user input is not an exceptional condition so validation functions should generally not throw exceptions. That's why methods like TryParse were added to the Framework (the original Framework didn't have them, and it made validation cumbersome because of all the possible exceptions).

陌伤浅笑 2024-09-24 06:40:11

代码契约用于断言始终正确的事物,如果它们不正确,则代码中存在错误。这意味着它只能适用于由代码控制的条件。因此,您不能使用它们来声明“用户永远不会提供空字符串”,因为这超出了代码的控制范围。静态验证器永远无法证明该陈述 - 它如何知道用户会做什么?

您可以做的就是做出诸如“给定用户输入,该方法将返回非空字符串或引发异常”之类的语句。

Code contracts are used to assert things that will always be true, and if they're not true, then there's a bug in the code. That means it can only apply to conditions that are controlled by code. So, you can't use them to state "the user will never supply an empty string", because that's outside of the control of the code. The static verifier will never be able to prove that statement - how can it know what the user will do?

What you can do is make statements like "Given a user input, the method will either return a non-empty string or throw an exception".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文