且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

参数验证***实践

更新时间:2023-02-26 19:06:25

通常参数检查非常便宜,即使调用数千次.例如测试一个值是否为空,一个字符串或集合是否为空,一个数字是否在给定范围内.

Usually parameter checks are very cheap, even if called thousands of times. For example test if a value is null, a string or Collection is emtpy a number is in a given range.

但要注意检查可能昂贵,所以请三思:评估大字符串上的正则表达式,检查文件是否存在,检查集合中的所有元素符合一定条件.

But beware that checks may be expensive, so think twice: Evaluating a regex on a large string, checking if a file exists, checking that all elements in a collection meets a certain criteria.

我还建议仅在公共或受保护方法中进行检查.请注意,所有带有未检查参数的公共方法都是潜在风险

I would also only recommend checking only in public or protected methods. Note that all public methods with unchecked parameters are potential risks!

编辑/另一个想法:如果一个方法不使用参数,而是只是将其传递给另一个方法,那么您也可以省略检查.只有实际使用这些参数的方法才应该进行检查.

EDIT/another thought: If a method does not use the parameters but is just passing it to another method then you may also omit the checking. Only the method which is actually using these parameters for itself should do the checking.

这是因为如果参数的要求发生变化,您需要在多个地方更改验证,存在不一致的风险.

This is because if the requirements of the parameters change you need to change the validations in multiple places, risking inconsistency.