mardi 28 janvier 2020

Chain of Responsibility Pattern - Returning a value/result

I'm trying to implement a Chain of Responsibility solution but I have some doubts about the result/returning value.

I would return a result to the caller to understand the result of the validation done during the Chain.

For example:

public class DataObjectToValidate {}

public class DataObjErrorValidation {}


public class DataObjectValidationResult {

    public Boolean isValidationOK;
    public DataObjErrorValidation;
}

public interface ValidationChain {

    void setNextChain(ValidationChain nextChain);

    void validate(DataObjectToValidate objToValidate);
}


public class Validation1 implements ValidationChain {

    private DispenseChain chain;

    @Override
    public void setNextChain(ValidationChain nextChain) {
        this.chain = nextChain;
    }

    @Override
    public void validate(DataObjectToValidate objToValidate) {

        //Execute the first step validation using objToValidate parameter

        //If the first step validaiton fails, I would return a DataObjectValidationResult obj
        //with the isValidationOK parameter set to false and the DataObjErrorValidation contains
        //the info regarding the failure
        //else I will call the next step
    }
}


public class Validation2 implements ValidationChain {

    private DispenseChain chain;

    @Override
    public void setNextChain(ValidationChain nextChain) {
        this.chain = nextChain;
    }

    @Override
    public void validate(DataObjectToValidate objToValidate) {

        //Execute the second validation step using objToValidate parameter
        //If the second step validaiton fails, I would return a DataObjectValidationResult obj
        //with the isValidationOK parameter set to false and the DataObjErrorValidation contains
        //the info regarding the failure
        //else I will call the next step
    }
}


public class Validator {

    private ValidationChain c1;

    public executeValidation() {

        ValidationChain c1 = new Validation1();
        ValidationChain c2 = new Validation2();

        DataObjectValidationResult objErrorValidation = c1.setNextChain(c2);
    }
}

Using this approach, the caller will receive a DataObjectValidationResult object from the Chain and understand if the validation was successful and which error happened.

What do you think about this approach? Does it make sense or am I violating some rules?

Thanks

Aucun commentaire:

Enregistrer un commentaire