vendredi 20 mars 2020

Java design class with same validation rules for different types of objects

I'm trying to design a class with several simple validation rules. These rules can be applied to different Hibernate entities (or DTOs) and I'd like to unify this class without creating different implementations.

I try to do this by using generics, but the problem is although each type of the validated object has particular getter (getCatalog), I can't call it using generics without implementing a common interface or extending an abstract class. I think interface for entity/dto in such case is not a good choice.

Validator class

public class Validator<T> {

public boolean validate(List<T> objects, Function<T, Catalog> catalogGetter) {

    if (CollectionUtils.isEmpty(objects)) {
        return false;
    }
    if (differentCatalogsInLoadExist(objects, catalogGetter)) {
        return false;
    }
    if (catalogForObjectNotExists(objects, catalogGetter)) {
        return false;
    }
    return true;
}

private boolean differentCatalogsInLoadExist(List<T> objects, Function<T, Catalog> catalogGetter) {
    return objects.stream()
            .map(catalogGetter)
            .map(catalog -> catalog.getCatalogCode())
            .distinct()
            .count() > 1;
}

private boolean catalogForObjectNotExists(List<T> objects, Function<T, Catalog> catalogGetter) {
    return objects.stream()
            .map(catalogGetter)
            .findFirst()
            .isEmpty();
}

}

My main goal is to get rid of this Function<T, Catalog> catalogGetter because it looks not as good as it could be..

Aucun commentaire:

Enregistrer un commentaire