lundi 30 mars 2015

Best Practices - Spring Framework - Should Validation Be implemented in Business Service Or Be In Separated?

Recently I've run into a debate with one of my colleagues about where we should keep business validations. I have searched on stackoverflow for similar questions but none of them gives me a comparison between the 2 approaches which I'm gonna explain.


Approach 1: Validation should be separated from the business service (my approach)


We have a Spring Rest application. I use the interface org.springframework.validation.Validator. Let's call the validator as CreateUserValidator. And the business rule is email address has to be unique.


I then hooked up the validator to the controller by InitBinder as follows:



@Autowired
private CreateUserValidatorvalidator;

@InitBinder
private void initBinder(WebDataBinder binder) {
binder.addValidators(validator);
}

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<User> createUser(
@Valid @RequestBody User user)
throws MethodArgumentNotValidException {
logger.debug("Creating User");

user = userService.createUser(user);

return new ResponseEntity<User>(user, HttpStatus.OK);

}


Pay attention to @Valid in the method createUser(). It means that the user object will be validated through a series of validators (Hibernates, Spring,...) and my validator which is CreateUserValidator.


Hence, the userService doesn't have to do the validation jobs.


Approach 2: Validation should be in the Service Layer.


For this, please look at the code below:



@Override
public User createUser(final User user) {
if(this.findByName(user.getName())!=null){
throw new DuplicateKeyException("user.name.duplicate",new Object[]{user.getName()});
}
return userRepository.save(user);
}


The whole idea is validation should be in the service.


Arguments


Approach 1:



  1. Pros

    • Clearer

    • Validators can be reused



  2. Cons

    • If we expose the service as an API, we are missing the validations




Approach 2:




  1. Pros



    • Validations are bound to Service




  2. Cons



    • Validators cant be reused

    • Mix of validations and business code in the service




Can you give your opinions on this?


Thanks,


Aucun commentaire:

Enregistrer un commentaire