Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 validateclass 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?

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.