3
\$\begingroup\$

I am a bit confused with Controller Service Dao implementation . I created a dummy User servlet along with Model controller dao and a service , though it will work , but is it the right approach. I am still confused about the purpose of service class

//user registration Service
//add user , delete user
@WebServlet("/useraction")
class UserController
{
    UserService userService = new userService();    
    int id = request.getParameter("id");

    userService.userAction(int id,String action);
    //minimum code for sake of question  
}

class UserService
{
    UserDao userDao = UserDaoImpl.getInstance();

    void userAction(int id,String action)
      switch(action){
       case "add" :
         userDao.addUser(id);
         break;
       case "delete" :
         userDao.deleteUser(id);
         break;
       default :
         throw IllegalArgumentException();     
      }
    }
}

interface UserDao
{
    void deleteUser(int id);
    void addUser(int id);
}

class UserDaoImpl implements UserDao
{
    private static UserDaoImpl userDaoImpl = new UserDaoImpl();

    public static UserDaoImpl getInstance(){
        if(userDaoImpl == null)
            userDaoImpl = new UserDaoImpl();
        return userDaoImpl;
    }

    void deleteUser(int id){
        //some validations and db activity
    }

    void addUser(int id){
        //some validations and db activity
    }

}

//Model
class User
{
    private int id;
    private String name;
    private String email;
    //a lot more parameters
}

Questions i want to ask :

  • Is this the right approach for Controller dao service pattern?
  • Purpose of service class , is it for redirection only to dao or for validations also
  • Do we need to use inheritance for Dao classes ?

Thanks in Advance

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

There are various implementations of MVC or MVC inspired patterns, there aren't hard and fast rules to follow, each implementation is often tweaked to suit certain needs.

Here are some old threads that explain the responsibility of each layer and may answer some of your questions:

Is this the right approach for Controller dao service pattern?

MVCS - Model View Controller Service

Responsibilities and use of Service and DAO Layers

Purpose of service class , is it for redirection only to dao or for validations also?

Service layer vs DAO — Why both?

In MVC , DAO should be called from Controller or Model

Do we need to use inheritance for Dao classes ?

Most effective way to reflect inheritance relationship in DAOs?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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