mercredi 29 avril 2020

How can remove conditional statements while adding the common responsibilitu to the class?

I am building up a validation engine. There are common rules, which I have consolidated in a parent interface static method.

public interface EmployeeValidator {
    Predicate<Employee> build(Employee employee);

    static Predicate<Employee> getCommonRules(Employee employee) {
        return validateAge().and(validateGenger());
    }

    private static Predicate<Employee> validateAge() {
        ...
    }

    private static Predicate<Employee> validateGenger() {
        ...
    }
}

Now, the class that implements this interface will add more validation rules to it. There will be multiple implementations of EmployeeValidator

class BackOfficeStaffValidator implements EmployeeValidator {

    @Override
    public Predicate<Employee> build(Employee employee) {
        return EmployeeValidator.getCommonRules(employee).and(validationsOnDirectReports());
    }

    private Predicate<Employee> validationsOnDirectReports() {
        ...
    }
}

But the problem with this approach, at the client. I need conditional statements or switch case to select the proper implementation.

Employee employee = ...;

if(employee.staffType() == StaffType.TECHNICAL) {
    Predicate<Employee> build = new TechnicalStaffValidator().build(employee);
} else if(employee.staffType() == StaffType.BACK_OFFICE) {
    Predicate<Employee> build = new BackOfficeStaffValidator().build(employee);
}

is there a way to improve my current design? If the current approach is moving in the right direct suggest an alternate approach.

Aucun commentaire:

Enregistrer un commentaire