jgwmdfuysqkxbvah
jgwmdfuysqkxbvah

Reputation: 26

What is the limit about testing/checking variables?

I have a javascript class which can be extend.

When I was writing unit tests, I see errors I can catch.
So I add tests for checking class attributes in my first function extractParameterMethodForRequest.
But now when I read my function there is a lot of noise.

Do you think it's useful to check like this? maybe I have to merge some exception to provide generic error?

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];
};

Upvotes: 0

Views: 70

Answers (1)

rsp
rsp

Reputation: 111444

There is no limit about testing/checking variables. But if you feel that it makes your function less readable then you can always take the parameter checking code someplace else.

Also, you can write it in a much shorter way. For example this:

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

could be written as:

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

or even:

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

The way that it is written right now is very verbose.

Upvotes: 1

Related Questions