I'm feeling a little conflicted at the moment. I have a web application using Stripes for an MVC framework and Spring/Hibernate for the back-end. I have an account registration method in my MVC layer which requires the following validation:
I have a validation method in Stripes (MVC layer) that checks these two cases but was wondering whether my service layer should duplicate these checks? If the service layer interface was exposed as a web service then I think the validation would be a good idea, but if it's only used in the context of a web application is it required?
Edit: I'm not intending to duplicate the validation code - I mean duplicating the validation method calls in two places.
I see my options as:
What's best practice here? I'm looking for advice/opinions on which option I should go with and why.
Note that there are simple validation checks on the input fields of the registration form (like checking for blanks) and that I think these should be handled by the MVC validation only; I'm only concerned about more complex validations.
As a general rule of thumb, I would say that business logic of this sort should be in the service. Controllers should be light-weight and pass on requests. Further, there may be other clients of your service, not just controllers, so this allows you to keep validation in one place. Save this answer.
A service layer is an additional layer in an ASP.NET MVC application that mediates communication between a controller and repository layer. The service layer contains business logic. In particular, it contains validation logic. For example, the product service layer in Listing 3 has a CreateProduct() method.
The first step to enable validation in a controller is to add @Valid to a method parameter that is created using model binding. In lieu of explicit validation error handling (which we will cover below), Spring Boot throws an exception if validation fails for the new object.
Don't duplicate code. Use JSR303 Bean Validation so you can use the same validation logic in all layers of your app.
Hibernate Validator (a separate project from the Hibernate ORM stuff) provides the reference implementation of this interface. It is dead simple to use, you can get started with it very quickly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With