在使用数据的每个级别都进行数据验证是否更好?

发布于 2024-09-07 08:00:43 字数 84 浏览 6 评论 0原文

如果您有一系列对某些数据进行操作的函数,那么最好让每个函数在使用数据之前验证数据是否有效,或者在链的开头进行验证并使链中的每个函数都“信任”它是有效的吗?

If you have a chain of functions that operate on some data, is it better to have each function verify the data is valid before using it, or do that verification at the start of the chain and have every function in the chain just "trust" that it is valid?

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

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

发布评论

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

评论(2

四叶草在未来唯美盛开 2024-09-14 08:00:43

应用防御性编程始终是一个好习惯。您应该考虑所有可能的情况。

如果输入来自用户,验证就变得非常重要,在这种情况下,您必须确保您的代码知道在每个无效数据场景中要做什么。对您可以预测的情况尝试断言,对不可预测的情况尝试例外,详细信息取决于您使用的语言。这是防弹计划的基础。

Is always a good practice to apply defensive programming. You should contemplate all possible scenarios.

The validation gets extremely important if the input comes from an user, in that case you must make sure that your code knows what to do in each invalid data scenario. Try assertions for the situations you can predict and exceptions for the unpredictable ones, the details would depend on the language you're using. This is the foundation of a bulletproof program.

沙沙粒小 2024-09-14 08:00:43

链上的较低层函数是否被自己调用将在很大程度上影响您的决定。如果您有一个严格分层的系统,其中某些类仅由程序的其他类调用,则这些内部类可以进行更轻松的数据检查并“信任”数据。

来自 Steve McConnell 的《Code Complete 2》:

“出于防御性编程目的设置路障的一种方法是将某些接口指定为‘安全’区域的边界。检查跨越安全区域边界的数据的有效性,并在数据不符合要求时做出明智的响应。无效。

可以在类级别使用相同的方法。类的公共方法假定数据不安全...一旦数据被类的公共方法接受,类的私有方法就可以假定数据是安全的。 ”

Depending on whether the lower functions on the chain are called by themselves will largely influence your decision. If you have a rigidly tiered system with certain classes only being called by other classes of your program, those inner classes can have much lighter data checking and "trust" the data.

From "Code Complete 2" by Steve McConnell:

"One way to barricade for defensive programming purposes is to designate certain interfaces as boundaries to 'safe' areas. Check data crossing the boundaries of a safe area for validity and respond sensibly if the data isn't valid.

The same approach can be used at the class level. The class's public methods assume the data is unsafe...Once the data has been accepted by the class's public methods, the class's private methods can assume the data is safe."

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