Search code examples
javaspringarchitecturebusiness-logic

Service layer and controller: who takes care of what?


In class we're now learning how to build up a Spring application, even though spring isn't directly involved, we learned how to make the interfaces for DAO and service layer objects.

Please correct me if I'm wrong: DAO layer is pretty abstract: it just contains the CRUD operations and is further used to read data.(ie: get all objects, get specific objects, etc)

Service layer: contains services to create things, and delete things, this is where business logic should be.

Now all of this makes sense in the service layer; except "updating" objects. Do you just put a "update" function that just saves the object in your database? Or do you need to define the logic there as well? This is where my confusion is as, my understanding is objects in Spring are just POJO's. Now then who validates the data?

Let's say I have an Object "child" it has:Name, SurName, Gender, Photo, Birthdate fields. how would I name the services? Or would you just let the controller take care of validation, which doesn't seem right to me. On the other hand it wouldn't seem right either to delegate every setter that needs to be called to the service layer.

So just basically: help me with how to define saving your objects via the service layer.


Solution

  • If you wish to have controllers be able to persist changes to a Child object, then traditionally you would have a method in the service named something like ChildService.update(Child newchild), which will handle calling the correct DAOs to persist the new version of this Child.

    Controllers are free to ask the service for a Child, change the fields around (conceivably based on some user input) - a sane design would have the Controller doing some work with the Child POJO and then asking the Service to persist the change. The model POJO should know nothing about a controller, service, or DAO but just simply hold data as you suggest - certainly you would not want every call to setName() or setGender() to automatically result in a database update.

    Instead, the controller and/or service should acquire a Child object, do whatever work it needs to the object in it's unit of work, and then ask a Service (and then the DAO) to persist the changes.

    Validation can take place in several layers - the Controller might want to validate any input from the web user, and the Service may want to validate that it has a valid Child object before it persists it. It especially makes sense to have some level of validation in both layers in case you want to re-use this Service in other capacities - such as exposing a REST interface, a different front-end, etc.