【发布时间】:2009-09-15 22:01:33
【问题描述】:
是的,正确阅读。上次我在 JavaScript(函数)中看到了不同的参数验证模式,并想知道其中哪一个是最佳实践。首先,我将展示两个示例代码 sn-ps。第一个显示(用我的话)“立即”参数/条件验证,第二个显示“延迟”验证。它们中的每一个都以不同的方式影响以下代码的外观。到目前为止,我一直使用“立即”验证。但是慢慢地,我开始怀疑将整个以下代码强制进入这样的条件块是否合理。请告诉我您的想法以及可能是“最佳”模式。
那么声明变量的地方呢?有几次我读到,所有变量都应该在实际使用之前声明到方法上。它是否正确?因为我认为在确定变量会被实际使用之前声明变量是没有用的(可能无效的参数会强制抛出异常),所以我将变量声明部分移到了参数/条件验证部分之外。这是可取的吗?
谢谢!
第一个例子:
if ( colorStops.constructor === Array
&& colorStops.length
&& colorStops.every(function(c) {
return c instanceof ColorStop
}))
{
var privateVar1 = "foo",
privateVar2 = "bar",
privateVar3 = "tutifrutti";
// here goes the code
}
else {
throw new TypeError("GradientCanvasFacade: cannot add Colors; " +
"invalid arguments received");
}
第二个例子:
if (cg instanceof ColorGradient) {
throw new TypeError("PresetManager: Cannot add preset; " +
"invalid arguments received");
}
var privateVar1 = "foo",
privateVar2 = "bar",
privateVar3 = "tutifrutti";
// here goes the code
// Here goes the code that get executed when no explicit
// return took place ==> all preconditions fulfilled
【问题讨论】:
-
无论如何,不要使用“构造函数”。它不是在所有浏览器中,当它出现时,它根本不像听起来那样。坚持使用本机 JS 对象的 instanceof。
标签: javascript validation parameters arguments