Search code examples
springvalidationspring-mvcdesign-patternsrpc

Where should the validation be, in the MVC layer or in the business engine?


A web application backend coded in Spring makes remote procedure calls to a "business engine" which performs intensive calculations.

These intensive calculations have a high error rate mostly because of bad requests from the backend to the engine and/or bad/insufficient data in the DB.

Because of that, it is necessary to provide error codes that can be converted into messages to the user to help identify the problem.

     ----------         -----------          ----------
    |          |       |           |        |          |
    |   USER   | ----> |  BACKEND  | -RPC-> |  ENGINE  |
    |          |       |           |        |          |
     ----------         -----------          ----------
                             |                    |
                             |                    |
                           -----                -----
                   Config |     |     Business |     |
                   DB     |     |     DB       |     |
                           -----                -----

It is my opinion that the validation should occur before making the call to the engine in order to fail fast and avoid waiting for a response that is going to fail inevitably after being sent, queued depending on the load, processed and returned to the backend.

Question: should the validation occur in: A) the backend or B) the business engine?

Bonus question: if the answer was B), should the business engine return the error code and let the backend handle the conversion, or also implement the i18n of the messages?

Additional information:

  • The validation logic is no secret and is known both in the backend and the business engine.
  • The configuration data used in calling the engine via RPC is owned and stored by the backend (the engine has no access other than the request).
  • i18n of the errors is required.

Opinion and/or alternatives for/against any of the approaches is welcome. Thank you.


Solution

  • should the validation occur in: A) the backend or B) the business engine?

    Yes.

    Do validation in multiple places. Validate on the client for quick feedback. Validate in your controllers for security, validate in your repositories for data integrity. You know about JSR Validation Groups, right?

    should the business engine return the error code and let the backend handle the conversion, or also implement the i18n of the messages?

    Stick with JSR validation to start. It's pretty good. It throws exceptions when there's a validation error. Keep your error messages in properties files.