-2

I have the following situation: I have to validate a Token using (for now) 2 different strategies, they both do the same thing (check if the token is valid) but in different ways.

My current way of dealing with the strategy instantiation looks like this:

@Service
public class ValidationService {
    private Map<ValidationType, ValidationStrategy> validationMap = new HashMap<>();

    public ValidationService() {
        validationMap.put(ValidationType.A, new AValidationStrategy());
        validationMap.put(ValidationType.B, new BValidationStrategy());
    }

    public void validate(ValidationType type, String token) {
        ValidationStrategy strategy = validationMap.get(type);
        if(strategy == null) {
            strategy = new NoValidationStrategy();
        }
        strategy.validate(token);
    }
}

My question is: Is there a prettier way to set up the proper validation according to the ValidationType enum? Because the constructor would grow more and more as new validation strategies would be added in the system.

I thought that maybe I could keep that Map<> variable and add new Strategy instances when the ValidationService bean would be created by some sort of Spring Boot configuration, but I don't know how I could access the Bean after its instantiation by Spring Boot.

Help me out if you have a better way of doing this! :)

PS: Any code snippets or useful links would be greatly appreciated!

1 Answers1

0

Absolutely, one option is Reflection. Every ValidationStrategy could define a ValidationType either as a Method or through an Annotation, assuming ValidationType is an enumeration. You could then find all ValidationStrategy and group them to a Map based on type. This would solve the problem of having to update the map every time a new validation strategy is added.

Jason
  • 5,154
  • 2
  • 12
  • 22
  • Yes, ValidationType is an enum, and I like the idea of using an Annotation to find all the ValidationStrategy class implementations, maybe something like @ValidationStrategy(ValidationType.A). But where could I put the code to find the classes annotated and add them to the service map attribute? Like, where do I "tell" spring boot that this code needs to be executed – Gustavo Maciel Jun 30 '20 at 14:35