I have a validator class, whose purpose is to validate input data. Initially I wrote the class like this:
export class ValidatorForInputs {
constructor(inputData) {
this._data = inputData;
}
validate() {
let results = {};
let validateInputDataForMissingKeys = checkInputDataForMissingKeys(this._data);
if (validateInputDataForMissingKeys) results = { ...results, ...validateInputDataForMissingKeys };
let validateInputDataForMissingValues = checkInputDataForMissingValues(this._data);
if (validateInputDataForMissingValues) results = { ...results, validateInputDataForMissingValues };
let validateInputDataMaximums = checkInputDataMaximums(this._data);
if (validateInputDataMaximums) results = { ...results, validateInputDataMaximums };
return results;
}
}
to be called like this:
let validatorForInputs = new ValidatorForInputs(inputData);
let validationForInputsResult = validatorForInputs.validate();
// do something with validationForInputsResult
But then I wondered, is the constructor really necessary when the data could be passed directly to the validate
method like so:
export class ValidatorForInputs {
validate(data) {
let results = {};
let validateInputDataForMissingKeys = checkInputDataForMissingKeys(data);
if (validateInputDataForMissingKeys) results = { ...results, ...validateInputDataForMissingKeys };
let validateInputDataForMissingValues = checkInputDataForMissingValues(data);
if (validateInputDataForMissingValues) results = { ...results, validateInputDataForMissingValues };
let validateInputDataMaximums = checkInputDataMaximums(data);
if (validateInputDataMaximums) results = { ...results, validateInputDataMaximums };
return results;
}
}
and then called like this:
let validatorForInputs = new ValidatorForInputs();
let validationForInputsResult = validatorForInputs.validate(inputData);
// do something with validationForInputsResult
or even called in a one liner like this:
let validationForInputsResult = ( new ValidatorForInputs() ).validate(inputData);
// do something with validationForInputsResult
With a little bit of testing, I found that the code behaves the same way. I read the what the docs have to say about constructors but did not find any information that answers this question.
So, in a case like this, should a constructor be used or not? If so, why? If not, why not?