I have some validation classes. To keep things smooth, I create a single class that has those validation classes inside of it. That class will be a singleton, and gets injected into my other classes.
The validation classes have a method that needs to be executed by the depending object. So lets make this clear:
The Matrix
class
Gets a validate
class injected
and calls validate.validateMatrix()
.
That method, validateMatrix()
, is actually in another class, that validate
imports and creates a reference to. The validateMatrix
class, for example, looks like this:
export class validateMatrix {
validateMatrix(props){
...
}
}
The validate
class has a generator for those classes that it needs, and all the validation classes have a method with the exact same name as the class name. That way, I can request the class name and call out to the validate method. That class looks like this:
import {validateString} from './validate/validateString';
import {validateSlider} from './validate/validateSlider';
import {validateCheckbox} from './validate/validateCheckbox';
import {validateRadio} from './validate/validateRadio';
import {validateDatetime} from './validate/validateDatetime';
import {validateMatrix} from './validate/validateMatrix';
export class validate {
// this is just the library containing all the validators, for easy import.
constructor(){
this.classGenerator(
validateString,
validateSlider,
validateCheckbox,
validateRadio,
validateMatrix,
validateDatetime
);
}
classGenerator(...classes){
// pass in a class with the same method name as class name
// and that function will be referred from here
// e.g. this.validateMatrix()
classes.forEach( (theClass) => {
let classObj = new theClass();
this[classObj.constructor.name] = classObj[classObj.constructor.name];
});
}
}
Usage:
validate() {
this.validator.validateMatrix(this.question.properties)
.then(this.branching.branch());
}
Is this a good way to create a factory method to generate those methods, and keep them hidden in other classes?