简体   繁体   中英

Is user class responsible for authentication?

I have class named User , it has fields like username, password, firstName... . is it good to place authenticate(username, password) method in it?

Ideally no, that should be the job of the controller. User class should be just a data class, which is used by the controller (the business logic class) to evaluate things like Authenticate etc.

Explanation:

You need to modularize your code(break it into components) and each component should be an independent entity but requires other components to give the whole picture of the system.

It appears by your question that you want to perform some business layer operation in your DO(data object) class. It can be done but is never recommended as it kills the idea of separation of concerns.

As for controllers, you could do something like

  • Have object/entity level managers, ie, for every entity you have a manager to handle its business logic stuff. Say for a User class you have a UserManager.

  • Have conceptual level controllers. This means that you have controllers that handle a specific module of your system(an entire concept). For example, if you have a website that needs to authenticate users, you can have an AuthenticationController. Now, Authentication must not necessarily map to just one table/object, though it appears that its sole target is(logically) your User table/class etc, it could be doing other stuff and accessing other entities(depending on the requirement) etc. So by having entity level managers that are used by conceptual level controllers, you could ease your development.

I would say no. Better is to have a Connection and create a user using login method with username and password:

class Connection{
public:
 Connection(string connectionString);
 User login(string userName, string Password);
};

That would break the MVC (Model View Controller) structure. It is best to keep these three separated for code elegance, readability, and maintainability. A quick example would be, in Java:

Model:

public class User {

   private String username;
   private String password;
   (...)

}

Controller:

import yourmodelpackage;

public class MyController {

   public static boolean authenticate(String username, String password) {
      //your logic
   }

}

View:

//call your authenticate() method through the controller
MyController control = new MyController();
boolean b = control.authenticate(username, password);

There are a few design patterns that maximize the use of inheritance for this structure. I'd recommend looking into the Decorator Design Pattern .

如果您绝对希望将验证封装在该类中,则可以在User类上User hasPassword(string password)方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM