gpt4 book ai didi

javascript - 测试/检查变量的限制是什么?

转载 作者:行者123 更新时间:2023-12-03 05:36:18 25 4
gpt4 key购买 nike

我有一个可以扩展的 javascript 类。

当我编写单元测试时,我看到了可以捕获的错误。
因此,我在第一个函数 extractParameterMethodForRequest 中添加了用于检查类属性的测试。
但现在当我阅读我的函数时,有很多噪音。

你觉得这样检查有用吗?也许我必须合并一些异常才能提供一般错误?

function MyClass(){
this.validHttpMethods = ['GET', 'POST'];
this.defaultValues = {
method: 'GET'
};
}

/**
* Extract "method" from parameters
* @param {MyClass~RawParameters} parameters
* @return {string} A validate Methods belong to validHttpMethods
*/
MyClass.prototype.extractParameterMethodForRequest = function (parameters) {
var idx;
var method;

if(parameters === undefined || parameters === null) {
throw Error('REQ-001 parameters undefined');
}

if(parameters.method) {
if(typeof parameters.method !== 'string') {
throw Error('REQ-002 method not a string');
}

method = parameters.method;
}
else {
if(this.defaultValues === undefined) {
throw Error('REQ-003 this.defaultValues undefined');
}

if(this.defaultValues.method === undefined) {
throw Error('REQ-004 default method undefined');
}

if(typeof this.defaultValues.method !== 'string') {
throw Error('REQ-005 default method not a string');
}

method = this.defaultValues.method;
}

method = method.trim().toUpperCase();

if(method.length < 1) {
throw this.RError('REQ-006 method empty');
}

if(this.validHttpMethods === undefined) {
throw this.RError('REQ-007 this.validHttpMethods undefined');
}

if(!(this.validHttpMethods instanceof Array)) {
throw this.RError('REQ-008 this.validHttpMethods not an array');
}

idx = this.validHttpMethods.indexOf(method);
if(idx === -1) {
throw this.RError('REQ-009 method %s invalid', method);
}

return this.validHttpMethods[idx];
};

最佳答案

测试/检查变量没有限制。但如果您觉得它使您的函数可读性较差,那么您可以随时将参数检查代码放在其他地方。

此外,您还可以用更短的方式编写它。例如这个:

if(parameters === undefined || parameters === null) {
throw Error('REQ-001 parameters undefined');
}
if(parameters.method) {
if(typeof parameters.method !== 'string') {
throw Error('REQ-002 method not a string');
}
}

可以写成:

if(!parameters || parameters.method && typeof parameters.method !== 'string') {
throw Error('bad arguments');
}

甚至:

assert(!parameters || parameters.method && typeof parameters.method !== 'string');

现在的写法非常冗长。

关于javascript - 测试/检查变量的限制是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40722913/

25 4 0
文章推荐: javascript - React 渲染函数阻止每次调用时创建新的 Canvas 元素 - Charts.js
文章推荐: javascript - 如何在字典中循环遍历字典列表并获取其中的值 - Javascript,用于 django 中的 ajax 调用
文章推荐: javascript - AngularJS 用