1

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?

5
  • 1
    Possible duplicate of Style for control flow with validation checks
    – gnat
    Commented May 17, 2017 at 17:11
  • ...as for Request I would most likely pass it via constructor parameter into that Specification class discussed in this answer
    – gnat
    Commented May 17, 2017 at 17:14
  • Does this mean that I have to create different specification classes for each condition? Doesn't it sound like an overkill?
    – sidgate
    Commented May 17, 2017 at 17:23
  • Are you able to create a subclass of Request, and add your validation functions to that instead?
    – Pete
    Commented May 17, 2017 at 17:23
  • you create one specification class for all conditions and one instance of that class per request
    – gnat
    Commented May 17, 2017 at 18:51

1 Answer 1

2

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
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.