0

I'm building a RESTful web api using Spring Microservices. I am following the Controller/Service/Repository Structure.

Where can I find some guidelines on what the responsibility of each class should be?

For example, say I'm implementing the following controller:

@RestController
@RequestMapping(value="v1/license")
public class LicenseController {

    @Autowired
    private LicenseService licenseService;

    @RequestMapping(value="/{licenseId}",method = RequestMethod.GET)
    public ResponseEntity<License> getLicense(@PathVariable("licenseId") String licenseId) {
        License license = licenseService.getLicense(licenseId);

I would like to know, for example, if the responsibility of validating the input falls on the controller, or the service.

Before attempting to return a reply, should I check in the Controller, or the Service whether the object exists? If no object found, should I throw an exception at Service level, or Controller level?

Where can I find answers to such questions?

Thanks in advance,

1 Answer 1

1

Congratulations, you have now entered what is called opinions in computerland!

Joke's aside, but your question is something that has been debated throughout years withing the computer community, which is "Where should validation be placed?"

And i can tell you that there is pro's and cons with both solutions.

Validation in controller:

Pro's:

  • early validation means we can fail fast, less resources used until we fail
  • internal logic can be much cleaner without having to validate among the logic
  • we only need to focus on logic in the component layer

Con's:

  • If we have multiple apis, REST, WebSocket, ProtoBuf we need to validate in multiple places.

Validation in Components/Business layer:

Pro's:

  • We always have validation, no matter how many different apis we add

Con's:

  • We need to mix business logic with validation
  • code can get messier
  • we are not failing fast which means we might use more resources until we fail

I can't give you a proper answer as this is very opinionated, and i cant point you to a resource that will tell you how to as this is constantly under debate. I have seen both implementations work perfectly in production systems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.