lundi 4 juillet 2016

Business logic validation patterns & advices

I have two layers of validation in my application. First is entity validation performed by bean validation API (e.g. required fields). The second level is business logic validation. For example, user has a post. User can delete a post only if he is a creator of this post and post rating < 50. So I have to do something like this:

if (post.getCreator().equals(session.getUser())) {
  if (post.getRating() < 50) {
    postRepository.delete(post);
  } else errors.add(400, "Cant delete post with rating 50 or higher")
} else errors add (400, "You should be owner of the post")

I don't like this way as this conditionals are reused and I have to duplicate code. Moreover, if number of conditionals is greater than 5 or so it becomes unreal to read and understand the code.

Moreover, standard Spring Validator won't be very helpful as I have to maker different validation for one entity on different actions (delete and update for example)

So I'm looking for a way to do this in a smarter way (pattern maybe) and I would be very grateful if someone could give me a hint.

Thank in advance!

Aucun commentaire:

Enregistrer un commentaire