vendredi 12 février 2021

Validation pattern using generics in Java - circular dependency

I have a set of tasks/commands where each is supposed to run some operations based on inputs. Each input have to be validated and then it can be accepted or rejestec. Input validation is not actually an input class problem so I externalized it to dedicated validation classes. Everythin is driven by Java generics. However Sonar complains there is circular dependency in my solution. I see it but have no idea how change my design to overcome this problem. Tried with different ideas but the code looks awful now.

Below is simplified code of current case:

public abstract class Task<T extends Setting> {
    private HashMap<String, Set<Setting>> settings;
    
    public void addSetting(String key, Setting setting) {
        if(setting.valid()) {
            settings.put(key, setting);
        }
    }

    public abstract void process(T setting);
}

public class ConcreteTask extends Task<ConcreteSetting> {
    @Override
    public void process(ConcreteSetting setting) {
        ...
    }
}

public abstract class Setting {
    private SettingValidator validator;

    protected Setting(SettingValidator validator) {
        this.validator = validator;
    }

    public boolean valid() {
        return validator.validate(this);
    }
}

public class ConcreteSetting {   
    // some fields
    ...

    public ConcreteSetting() {
        super(new ConcreteSettingValidator()); // circular dependency
    }
}

public interface SettingValidator<T extends Setting> {
    boolean validate(T setting);
}

public class ConcreteSettingValidator extends SettingValidator<ConcreteSetting> {
    @Override
    boolean validate(ConcreteSetting setting) { // circular dependency
        ...
    }
}

Aucun commentaire:

Enregistrer un commentaire