Best practice for passing data to the service layer

advertisements

I am working on a web application in spring following the MVC pattern and was wondering what is considered "best practice" for making a solid service layer. The reason for this question is the following example situation:

A page for editing user information is loaded. After this form is submitted I gather all of its data in my controller method in a specific Command class containing only the data needed for the action that follows (updating the user).

I can think of several situations now to pass this information to my service layer:

  • Passing the command itself: userService.save(command);
  • Passing a model class, fetched in the controller: userService.save(user);
  • Passing both a model class and the command: userService.save(user, command);
  • Passing all of the parameters individually: userService.save(command.getName(), ...)

In my opinion passing the command class itself looks like the most elegant solution as I can first validate all the values automatically using the framework then pass them to my service. My concern here is that when I call the method from another class (not through my form / controller) I can fill this command object with invalid data, resulting in possible errors in the service layer.

What would you recommend and why?


After seeing your I have the following ideas Passing the command itself: userService.save(command);

This may not be a goode idea since your Service layer is unnecessarily dependent on Command object

Passing a model class, fetched in the controller: userService.save(user);

I will vote for this. Service layer only what it really supposed to know

Passing both a model class and the command: userService.save(user, command);

No. Same as the first option

Passing all of the parameters individually: userService.save(command.getName(), ...)

Hmmmm... not sure.. May be a mainitenance overhead in future.

I think if you want to do the validation, Use validation util classes to do the validation
    which can be used for both Service and UI layer. Here a lot validation can be centralized.