Question:
Hello. There is some kind of constructor.
var Animal = function (data) {
this.name = data.name;
this.age = data.age;
this.kind = data.kind;
}
It is necessary to validate the input data. That is, make sure that typeof name === String
, typeof age === 'number'
and 1+['cat', 'dog', 'mongoose'].indexOf(kind)
. How to check this is obvious. The question is where to check. Directly in the constructor? Or like this:
var validate = function () {
if (typeof this.name !== 'string') throw new Error;
if (typeof this.age !== 'number') throw new Error;
if (-1 === ['cat', 'dog', 'mongoose'].indexOf(kind)) throw new Error;
},
Animal = function (data) {
this.name = data.name;
this.age = data.age;
this.kind = data.kind;
validate.call(this);
}
How do you do it right?
@eicto,
the difference in my and your code is also this – I first validate, and then I initialize
Animal = function (data) {
validate.call(this);
this.name = data.name;
this.age = data.age;
this.kind = data.kind;
}
Is the fact that validation takes place in the constructor is already considered a sign of gunkcode?
@Etki,
But if you don't strive to write perfect code right away – well, uh, it's sad.
Well, why would I raise this question at all, if I did not strive to write normal code initially))?
Answer:
To write validating code right away, without hesitation, but following certain rules, it is better to use TypeScript
or flow . As a matter of fact, it’s not so important where to check for the first time, but it’s reasonable to make the this.valid()
function in order to find out the status of the instance at any time, and this can be more useful than throwing exceptions. But if the idea is like this:
var Animal = function (data) {
if(data === null || typeof data !== 'object') throw new Error;
this.name = data.name;
this.age = data.age;
this.kind = data.kind;
this.validate();
};
Animal.prototype.validate = function () {
if (typeof this.name !== 'string') throw new Error;
if (typeof this.age !== 'number') throw new Error;
if (-1 === ['cat', 'dog', 'mongoose'].indexOf(kind)) throw new Error;
};