1

I have a validator library, that is sanitizing and validate strings. The validator functions are pushing a message to a array "errors" for every nonvalid input they find.

When validation on all input is complete I collect the errors in a variable like this:

var errors = validator.getErrors();

// Function definition
Validator.prototype.getErrors = function () {
    return this._errors;
}

The var "errors" will now be an array containing 0 to several string elements. Right after this I'm calling a function for emptying the errors in the validator.

validator.clearErrors();

// Function definition
Validator.prototype.clearErrors = function () {
  this._errors = [];
}

Question: Can i somehow re write the getErrors() function so that is also empty it's internal _errors variable?... Then I can remove the clearErrors function altogether.

Anders Östman
  • 3,702
  • 4
  • 26
  • 48
  • When I look at it I really dont know why i have `return this;` in the clearErrors function. This function should not really return anything. Just reset the internal variable. – Anders Östman Oct 16 '13 at 08:19

2 Answers2

5

Why not simply this ?

Validator.prototype.getErrors = function () {
    var r = this._errors;
    this._errors = []; 
    return r;
}

But conventionally, functions named getXXX should not have any side effects. Clearing the source in a getErrors function is a little surprising. If you want to keep only one function, you might call it something like popErrors for example.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • This is so easy when you explain it! Very good that you also give some advice regarding "good coding standards" and naming of functions! – Anders Östman Oct 16 '13 at 08:27
1

Why don't you clone the array of errors and then reset it before returning the cloned array values

How do you clone an Array of Objects in Javascript?

Validator.prototype.getErrors = function () {
    new_array = this._errors.slice(0);
    this._errors = [];
    return new_array;
}
Community
  • 1
  • 1
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • Why clone it ? That seems useless here. – Denys Séguret Oct 16 '13 at 08:23
  • @dystroy care to explain how? 'var r = this._errors;' will simply pass the reference of one array to another, so when this._errors changes, 'r' changes too – gurvinder372 Oct 16 '13 at 08:26
  • 1
    @gurvinder372 *this._errors = []* does not change the existing array, but creates a new one and points *this._errors* to it. The previous array stays unchanged. – Butt4cak3 Oct 16 '13 at 08:30