1

I have a question about where is the borderline between including some kind of code in Controller and Service. I think that i've included bussiness logic in the wrong place. Let me show you an example that i want to refactor, this is part of a handler method which receives lists (currentRoles, pendingOfAuthRoles..etc) to update user roles:

    //Insert new roles
    List<Role> storedRoles = userService.getRoles(username);
    List<Role> newAcceptanceRoles = new ArrayList<Role>();
    for(Role role : currentRoles){
        if(!storedRoles.contains(role)){
            if(roleService.getPolicies(role.getRoleName()).size()>0){
                userService.insertRole(username, role.getRoleName(), true, false);
                newAcceptanceRoles.add(role);
            }else{
                userService.insertRole(username, role.getRoleName(), true, true);
            }
        }
    }
    if(!newAcceptanceRoles.isEmpty())
        mailService.sendRoleAcceptanceEmail(ControllerUtils.getBaseURL(httpServletRequest), username, newAcceptanceRoles.toString(), userService.getUserByUsername(username).getEmail());

In this part of the code, i insert the new relations between the user and roles. Some roles needs admin authorization, so that, the USER_ROLE table has a flag in order not to include roles with authorized=0 as a current user roles through a view.

If the role is not stored as a user role i insert it by setting the auth flag to false, furthermore if the role needs authorization an email is sent to the admin.

Do I need a service method like...

updateUserRoles(currentRoles, pendingOfAuth, pendingOfAccept)

and do this kind of work in the service or not?

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
mannuk
  • 1,259
  • 5
  • 21
  • 43
  • yes, your services are too fine-grained, they're essentially daos. see http://stackoverflow.com/q/3885675/217324. just be careful about sending email (because it is obviously not transactional). – Nathan Hughes Sep 18 '13 at 12:28
  • Thanks @Nathan. Does the mailService would be a Component? i mean.. are services only for transactional operations? The MailService has Autowired services. – mannuk Sep 18 '13 at 12:33
  • 1
    Just saying be careful. Say you send an email in your service method, then when spring tries to commit the transaction rolls back. Your email is sent already -- if your email is supposed to go only if the transaction succeeds then you have a problem. – Nathan Hughes Sep 18 '13 at 12:42

0 Answers0