Should the Model class (in MVC) use a static or instance method?

In the context of MVC structure, should a static method or an instance method be used?

eg. Suppose the Users class and the getUserById() method that return the User class, which one is better?

 Users users = new Users(); User ret = users.getUserById(123); 

or

 User ret = Users.getUserById(123); 

Suppose there is no instance variable in the Users class, which one is better?

+6
source share
3 answers

I would lean towards the instance variable. Just because it will be easier to write tests. In addition, many modern server technologies (Spring, JavaEE, etc.) support beans / resource injection very well. What better supports this, rather than static methods.

+4
source

Not directly. In fact, you should look at the DAO (Data Access Object) template.

the model classes themselves are responsible only for the transfer of information from one logical instance to another and should contain only geter and setter methods.

DAO classes are responsible for saving the update or retrieving information from some data source (database). Here is an example DAO pattern:

 public class BookDAO { private PreparedStatement saveStmt; private PreparedStatement loadStmt; public DBBookDAO(String url, String user, String pw) { Connection con = DriverManager.getConnection(url, user, pw); saveStmt = con.prepareStatement("INSERT INTO books(isbn, title, author) " +"VALUES (?, ?, ?)"); loadStmt = con.prepareStatement("SELECT isbn, title, author FROM books " +"WHERE isbn = ?"); } public Book loadBook(String isbn) { Book b = new Book(); loadStmt.setString(1, isbn); ResultSet result = loadStmt.executeQuery(); if (!result.next()) return null; b.setIsbn(result.getString("isbn")); b.setTitle(result.getString("title")); b.setAuthor(result.getString("author")); return b; } public void saveBook(Book b) { saveStmt.setString(1, b.getIsbn()); saveStmt.setString(2, b.getTitle()); saveStmt.setString(3, b.getAuthor()); saveStmt.executeUpdate(); } } 
+2
source

If you have a user class and, for example, a Product class, and you have objects with identifiers, I would suggest expanding "User" and "Category" to have one getById method that received $ id to run.

This way you can use the same method in two different types of objects.

Hope this example makes sense:

 class User extends SuperClass { public function getTableName() { return 'table_name_for_user'; } public function getPK() { return 'primary_key_for_user'; } } class Category extends SuperClass { public function getTableName() { return 'table_name_for_category'; } public function getPK() { return 'primary_key_for_category'; } } class SuperClass { public function getById($id) { $query = $this->db->query("SELECT * FROM " . $this->getTableName() . " WHERE " . $this->getPK() . " = $id"); return $query->result(); } } 
+1
source

Source: https://habr.com/ru/post/943807/


All Articles