In term of a MVC framework, should I use a static method or instance method?
e.g. Assume a Users
class, and a method getUserById()
which return a User
class, which one is better choice?
Users users = new Users();
User ret = users.getUserById(123);
or
User ret = Users.getUserById(123);
Assume there is no instance variable in the class Users
,
which one is a better choice?
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class. Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods are faster but less OOP. If you'll be using design patterns, static method is likely bad code.
A static method can access only static members and can not access non-static members. A non-static method can access both static as well as non-static members. Static method uses complie time binding or early binding. Non-static method uses run time binding or dynamic binding.
Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.
I would lean toward instance variable. Simply because it will be easier to write tests for. Plus, a lot of the current server technologies (Spring, JavaEE, etc) support injecting beans/resource very well. Which better supports this rather than static methods.
Defiantly nope. Actually you should look at DAO (Data Access Object) pattern.
Model classes itself are responsible only for transferring information from one logic instance to another and should contain only geter and setter methods.
DAO classes are responsible for storing updating or retrieving info form some Data Source (database).Here is example of 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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With