2016-11-21 1 views
0

확장 할 수있는 자바 스크립트 클래스가 있습니다.변수 테스트/검사에 대한 제한은 무엇입니까?

단위 테스트를 작성할 때 실수를 발견합니다.
첫 번째 함수에서 클래스 속성 검사를위한 테스트를 추가합니다. 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 || parameters.method && typeof parameters.method !== 'string') { 
    throw Error('bad arguments'); 
} 

나 :

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

과 같이 쓸 수있다

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

가 지금 작성하는 방식은 매우 자세한입니다.

관련 문제