Clean Code 最佳实践,我应该在函数内还是在调用者中验证数据?

Clean Code best practices, should I validate data inside function or in the caller?

检查这个函数:

private string function(string currentRegion)
{
    if (string.isNullOrEmpty(currentRegion)) return;// Is it the best practice to validate it inside the function?

    return doSomething();
}

或者

if (string.isNullOrEmpty(region)) result = function(region); // Or here?

或者 both?

因为如果在函数内部验证那么哪个字符串是 return 如果无效?

因为如果调用方验证 => "I'm the function" 我必须验证它!

因为如果两种方式都使用,可能是冗余代码?

视情况而定。

如果是privatefunction/method,调用方可以检查参数,调用方检查应该就够了。当然你也可以检查里面的functions/methods,例如防止你自己犯错误。

并且,如果它是任何 public method/function,强烈建议检查此 function/method 中的参数,因为您不能假设它会被正确调用。

不信外传,不信未知代码,不信任何其他程序员在调用你的functions/methods ;) 几行代码和成本就可以实现对错误参数的保护这种保护的成本总是低于花在调试代码和调查问题上的时间成本。