What should be the best way to design a DAO class ?
Approach#1: Design DAO class as an object.
class Customer {
//customer class
}
class CustomerDAO {
public void saveCustomer(Customer customer) {
//code
}
public Customer getCustomer(int id) {
//code
}
}
//Client code
class client {
public static void main(String[] args) {
CustomerDAO customerDAO = new CustomerDAO();
Customer customer = new Customer();
customerDAO.saveCustomer(customer);
}
}
Approach#2: Design DAO class with static methods (aka static class)
class Customer {
//customer class
}
class CustomerDAO {
public static void saveCustomer(Customer customer) {
//code
}
public static Customer getCustomer(int id) {
//code
}
}
//Client code
class client {
public static void main(String[] args) {
Customer customer = new Customer();
CustomerDAO.saveCustomer(customer);
}
}
In approach#1, I have to create an object of DAO class in all the client code (other option is to pass the reference of DAO all around). while in approach#2, I do not have to create the object and the static methods can be designed with no state tracking.
So which approach is the best in design of DAO classes ?
I would recommend approach #1, but would use Spring for dependency injection rather than instantiating DAOs directly.
This way, for unit testing the client code, you can substitue mock DAOs, and verify that the correct DAOs are invoked with the appropriate arguments. (Mockito is useful here.)
If you use static methods, then unit testing is much more difficult, since static methods cannot be overridden.