Service layer and controller: who takes care of what?

toomuchcs picture toomuchcs · Oct 7, 2010 · Viewed 31.6k times · Source

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.

Answer

Nathan Hughes picture Nathan Hughes · Oct 7, 2010

Generally a Spring service is transactional. Things go into a particular service method because they ought to be grouped together in the same transaction. If you want to retrieve an object from the database, twiddle it, and save the new version, the retrieval and save ought to be in the same service method. So your service methods are determined according to what you need the application to do for the user.

I try to restrict controllers to doing work related to validating http parameters, deciding what service method to call with what parameters, what to put in the httpsession or request, what view to redirect or forward to, or similar web-related stuff.

As far as validation goes: Validating input parameters in the controller is a good thing to make sure nobody can break your application with bogus inputs. Validation in the controller tends to be about making sure the inputs are syntactically ok (including detecting injection attacks) while service-level validation is about making sure the state of things in the database is what you expect it to be.

So controllers contain web-framework infrastructure code, services contain application logic code.