alexanoid
alexanoid

Reputation: 25780

Spring service method and a complex validation logic/rules

At my Spring/Boot Java project I have a set of service methods, for example like a following one:

@Override
public Decision create(String name, String description, String url, String imageUrl, Decision parentDecision, Tenant tenant, User user) {

    name = StringUtils.trimMultipleSpaces(name);
    if (org.apache.commons.lang3.StringUtils.isEmpty(name)) {
        throw new IllegalArgumentException("Decision name can't be blank");
    }
    if (!org.apache.commons.lang3.StringUtils.isEmpty(url) && !urlValidator.isValid(url)) {
        throw new IllegalArgumentException("Decision url is not valid");
    }
    if (!org.apache.commons.lang3.StringUtils.isEmpty(imageUrl) && !urlValidator.isValid(imageUrl)) {
        throw new IllegalArgumentException("Decision imageUrl is not valid");
    }

    if (user == null) {
        throw new IllegalArgumentException("User can't be empty");
    }

    if (tenant != null) {
        List<Tenant> userTenants = tenantDao.findTenantsForUser(user.getId());
        if (!userTenants.contains(tenant)) {
            throw new IllegalArgumentException("User doesn't belong to this tenant");
        }
    }

    if (parentDecision != null) {
        if (tenant == null) {
            if (findFreeChildDecisionByName(parentDecision.getId(), name) != null) {
                throw new EntityAlreadyExistsException("Parent decision already contains a child decision with a given name");
            }
        } else {
            if (findTenantedChildDecisionByName(parentDecision.getId(), name, tenant.getId()) != null) {
                throw new EntityAlreadyExistsException("Parent decision already contains a child decision with a given name");
            }
        }

        Tenant parentDecisionTenant = tenantDao.findTenantForDecision(parentDecision.getId());
        if (parentDecisionTenant != null) {
            if (tenant == null) {
                throw new IllegalArgumentException("Public decision cannot be added as a child to tenanted parent decision");
            }
            if (!parentDecisionTenant.equals(tenant)) {
                throw new IllegalArgumentException("Decision cannot belong to tenant other than parent decision tenant");
            }
        } else {
            if (tenant != null) {
                throw new IllegalArgumentException("Tenanted decision cannot be added as a child to public parent decision");
            }
        }

    } else {
        if (tenant == null) {
            if (findFreeRootDecisionByName(name) != null) {
                throw new EntityAlreadyExistsException("Root decision with a given name already exists");
            }
        } else {
            if (findTenantedRootDecisionByName(name, tenant.getId()) != null) {
                throw new EntityAlreadyExistsException("Root decision with a given name for this tenant already exists");
            }
        }
    }

    Decision decision = createOrUpdate(new Decision(name, description, url, imageUrl, parentDecision, user, tenant));

    if (parentDecision != null) {
        parentDecision.addChildDecision(decision);
    }

    criterionGroupDao.create(CriterionGroupDaoImpl.DEFAULT_CRITERION_GROUP_NAME, null, decision, user);
    characteristicGroupDao.create(CharacteristicGroupDaoImpl.DEFAULT_CHARACTERISTIC_GROUP_NAME, null, decision, user);

    return decision;
}

As you can see, most of the code lines from this method are occupied with a validation logic and I continue to adding a new validation cases there.

I want to refactor this method and move validation logic outside of this method in a more appropriate places. Please suggest how it can be done with Spring framework.

Upvotes: 2

Views: 4216

Answers (1)

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44675

As chrylis mentioned in the comments, you can achieve this goal by using JSR-303 bean validation. The first step is to create a class that contains your input parameters:

public class DecisionInput {
    private String name;
    private String description;
    private String url;
    private String imageUrl;
    private Decision parentDecision;
    private Tenant tenant;
    private User user;

    // Constructors, getters, setters, ...
}

After that, you can start adding validation annotations, for example:

public class DecisionInput {
    @NotEmpty
    private String name;
    @NotEmpty
    private String description;
    @NotEmpty
    private String url;
    @NotEmpty
    private String imageUrl;
    private Decision parentDecision;
    private Tenant tenant;
    @NotNull
    private User user;

    // Constructors, getters, setters, ...
}

Be aware that the @NotEmpty annotation is not a standard JSR-303 annotation, but a Hibernate annotation. If you prefer using standard JSR-303 you can always create your own custom validator. For your tenant and your decision, you certainly need a custom validator. First of all create an annotation (eg @ValidTenant). On your annotation class, make sure to add the @Constraint annotation, for example:

@Constraint(validatedBy = TenantValidator.class) // Your validator class
@Target({ TYPE, ANNOTATION_TYPE }) // Static import from ElementType, change this to METHOD/FIELD if you want to create a validator for a single field (rather than a cross-field validation)
@Retention(RUNTIME) // Static import from RetentionPolicy
@Documented
public @interface ValidTenant {
    String message() default "{ValidTenant.message}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };
}

Now you have to create the TenantValidator class and make it implement ConstraintValidator<ValidTenant, DecisionInput>, for example:

@Component
public class TenantValidator implements ConstraintValidator<ValidTenant, DecisionInput> {
    @Autowired
    private TenantDAO tenantDao;

    @Override
    public void initialize(ValidTenant annotation) {
    }

    @Override
    public boolean isValid(DecisionInput input, ConstraintValidatorContext context) {
        List<Tenant> userTenants = tenantDao.findTenantsForUser(input.getUser().getId());
       return userTenants.contains(input.getTenant());
    }
}

The same can be done for the validation of the parent decision. Now you can just refactor your service method to this:

public Decision create(@Valid DecisionInput input) {
    // No more validation logic necessary
}

If you want to use your own error messages, I suggest reading this answer. Basically you create a ValidationMessages.properties file and put your messages there.

Upvotes: 3

Related Questions