主要委托给其他函数的函数是否应该检查其所有参数?

发布于 2024-10-21 21:19:04 字数 191 浏览 0 评论 0原文

如果有一个外部函数接受一堆参数并调用其他几个函数(我将其称为内部函数)并向它们传递其参数的子集,那么更好的做法是: 1) 验证外部函数中的所有参数 2)只需将参数子集传递给内部函数并在那里验证它们

我偏向第一种方法,但我发现自己在外部函数中重复内部函数的逻辑只是为了验证参数。另一方面,传递未经检查的参数会让我感到紧张,即使我计划在内部函数中捕获它们。

If there is an outer function that takes a bunch of parameters and calls out to several other functions (which I'll call inner functions) passing them sub-sets of its parameters, is the better practice to:
1) validate all the arguments in the outer function
2) just pass the sub-sets of arguments through to the inner functions and validate them there

I'm partial to the first method, but I find myself repeating logic from the inner functions in the outer function just to validate the arguments. On the other hand, passing unchecked arguments through makes me nervous even if I am planning on catching them in the inner functions.

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

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

发布评论

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

评论(1

失去的东西太少 2024-10-28 21:19:04

最重要的是:仅验证您的输入一次。如果用户只能访问外部函数(将其称为“公共”),请验证公共层上的输入并假设内部(“私有”)层中的参数正确。由于用户无法直接调用私有层,因此不可能有错误的数据泄漏到其中。您可以考虑在私有层中添加断言以防万一。

经验法则:确保每条路径始终在一个位置进行验证。这不会让你的代码的未来读者感到困惑。他们可以安全地假设参数已经在哪里经过验证以及何时应该验证它们。否则,这将导致防御性编程和大量样板文件(多次验证对性能的影响可能是最不重要的)。此外,验证相同的输入两次或多次不会增加任何额外的安全性。

跨越界限并定义契约非常重要——哪些方法允许什么样的输入。我什至看到了命名约定,例如参数/方法名称的 orNull 后缀和 try 前缀。

如果您更喜欢在最低级别进行验证(私有 - 实际使用数据的地方),这很好。但是,您最终可能会出现大量重复,因为来自公共层的相同值会将其自身分配到私有区域中的多个函数中。

Most importantly: validate your input once only. If the user can only access outer functions (call them public), validate the input on the public layer and assume parameters are correct in inner (private) layer. Since the user cannot invoke private layer directly, there is no chance of having incorrect data leaking into it. You might consider adding assertions in private layer just in case.

The rule of thumb: assure there is always exactly one place where the validation occurs for each path. This will not confuse the future readers of your code. They can safely assume where the parameters are already validated and when they should validate them. Otherwise this will lead to defensive programming and a lot of boilerplate (the performance impact of several validations is probably least important). Moreover validating the same input twice and more does not add any additional security.

It is important to cross the boundaries and define contracts - which methods allow what kind of input. I even saw a naming convention like orNull suffix and try prefix for parameters/method names respectively.

If you prefer validation on the lowest level (private - where the data is actually used), this is fine. But you might end up with lots of duplication as the same value from public layer distributes itself into several function in private area.

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