gpt4 book ai didi

javascript - 在仅供内部使用的代码中进行额外检查是否是一种好的做法?

转载 作者:行者123 更新时间:2023-11-28 12:47:52 25 4
gpt4 key购买 nike

是否有必要检查代码中的所有参数和其他条件,如果我知道,我永远不会传递错误的参数,它应该可以正常工作(假设我已经在该代码之外进行了一些检查)。

示例:

这段代码:

/**
* Applies function to all elements of array in specified
* context.
* If array is empty, returns null.
*/
MyNameSpace.foreach = function(arr, callback, context) {
if (!(arr instanceof Array)) {
throw new Error('first argument is not an array');
}
if (typeof callback !== 'function') {
throw new Error('callback is not a function');
}
if (typeof arr.length === 'undefined') {
throw new Error('Length undefined');
}

var con = typeof context === 'object' ? context : window;

var i = arr.length;
if ( i <= 0 ) {
return null;
}

for ( j = 0; j < i; j++ ) {
callback.call(con, j, arr[j]);
}
}

可能是:

MyNameSpace.foreach = function(arr, callback, context) {
var con = typeof context === 'object' ? context : window;

var i = arr.length;
if ( i <= 0 ) {
return null;
}

for ( j = 0; j < i; j++ ) {
callback.call(con, j, arr[j]);
}
}

最佳答案

这绝对是一个很好的做法。它可以提高应用程序的稳定性并帮助调试。缺点是它会使代码变得困惑(使其难以阅读),并且会影响性​​能(尽管对于大多数 JavaScript 应用程序来说,性能并不重要)。

你必须针对每种情况采取看法。这实际上取决于(1)参数不正确的可能性有多大以及(2)如果参数不正确将会造成多大的损害。

关于javascript - 在仅供内部使用的代码中进行额外检查是否是一种好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5603935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com