开发者

Should a function that primarily delegates to other functions check all of its arguments?

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 nervo开发者_如何学编程us even if I am planning on catching them in the inner functions.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜