Check preconditions in Controller or Service layer Check preconditions in Controller or Service layer spring spring

Check preconditions in Controller or Service layer


Ideally you would do it in both places. But you are confusing two different things:

  • Validation (with error handling)
  • Defensivie Programming (aka assertions, aka design by contract).

You absolutely should do validation in the controller and defensive programming in your service. And here is why.

You need to validate for forms and REST requests so that you can send a sensible error back to the client. This includes what fields are bad and then doing localization of the error messages, etc... (your current example would send me a horrible 500 error message with a stack trace if ProductInfo.name property was null).

Spring has a solution for validating objects in the controller.

Defensive programming is done in the service layer BUT NOT validation because you don't have access to locale to generate proper error messages. Some people do but Spring doesn't really help you there.

The other reason why validation is not done in the service layer is that the ORM already typically does this through the JSR Bean Validation spec (hibernate) but it doesn't generate sensible error messages.

One strategy people do is to create their own preconditions utils library that throws custom derived RuntimeExceptions instead of guava's (and commons lang) IllegalArgumentException and IllegalStateException and then try...catch the exceptions in the controller converting them to validation error messages.


There is no "better" way. If you think that the service is going to be used by multiple controllers (or other pieces of code), then it may well make sense to do the checks there. If it's important to your application to check invalid requests while they're still in the controller, it may well make sense to do the checks there. These two, as you have noticed, are not mutually exclusive. You might have to check twice to cover both scenarios.

Another possible solution: use Bean Validation (JSR-303) to put the checks (preconditions) onto the ProductInfo bean itself. That way you only specify the checks once, and anything that needs to can quickly validate the bean.


I think in your special case you need to to check it on Service layer and return exception to Controller in case of data integrity error.

@controllerpublic class MyController{@ExceptionHandler(MyDataIntegrityExcpetion.class)public String handleException(MyDataIntegrityExcpetion ex, HttpServletRequest request) {  //do someting on exception or return some view. }}

It also depend on what you are doing in controller. whether you return View or just using @ResponseBody Annotation. Spring MVC has nice "out of the box" solution for input/dat validation I recommend you to check this libraries out.

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/validation.html