Pergunta

I have a class similar to ServletFilter which has multiple validation on the input request

class TokenHandler implements SomeHandler{
  Response handle(Request request){
    if(paramXMissing(request)){
       return new Response(); // empty response
    }
    if(paramYGreaterThan100(Request request)){
       return new Response(); // empty response
    }
   //some more similar validation on request


  }
}

request parameter can be an instance of any subtype of Request. As most of the validation methods depend on Request instead of the Handler, this seems more like feature envy code smell. Had Request been a normal domain object I would have just Moved method to that class. But in this case, how do I refactor this code (Long method)? I am not sure if introducing a new Validator class would be a right choice.

Edit


I don't have just the validation, but also additional processing on request object, for instance, remove particular parameter from query string.

I actually think that introducing new classes for each specification would be an overkill. Is it really required? Any other alternative?

Foi útil?

Solução

I would create an interface for the Validator and create a list of specialized Vatidator objects:

 class TokenHandler implements SomeHandler{
   interface Validator{
     boolean isInvalid(Request request);
  }
  private final List<Validator> validators = Arrays.asList(
      (Validator)request->paramXMissing(request), 
      (Validator)request->paramYGreaterThan100(request),
      // Checks could also be implemented as separate classes or enum... 
    );

  Response handle(Request request){
    for(Validator validator : validators){
      if(validator.isInvalid(request)){
         return new Response(); // empty response
      }
    }
    // continue for valid response
  }
}
Licenciado em: CC-BY-SA com atribuição
scroll top