2016-11-21 44 views
0

我有一個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]; 
}; 

回答

1

對測試/檢查變量沒有限制。但是如果你覺得它讓你的函數更不可讀,那麼你總是可以把參數檢查代碼放在別的地方。

此外,您可以用更短的方式編寫它。例如這樣的:

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'); 

,這是正確的,現在寫的方式是非常繁瑣。