I'm wondering if it's a good practise to create default DAO interface instead of creating own interface for each class.
public interface DAO {
public void addItem();
public void updateItem();
public void removeItem();
public Object getItem(int id);
public Object[] getAll();
}
Now we can implement this interface by multiple classes. Of course this sollution has it's cons like downcasting during retrieving data but I think it's still more efficient and code clear. Is this a good way to go?
It provides more abstraction and flexibility to your code. The clients of your DAO interface do not need to know how it is implemented, but only the methods it provides. In the end, interfaces are a good practice for maintainability of your code.
The Data Access Object (or DAO) pattern: separates a data resource's client interface from its data access mechanisms. adapts a specific data resource's access API to a generic client interface.
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate, JPA or JDO in a consistent way.
DAO stands for Data Access Object. DAO Design Pattern is used to separate the data persistence logic in a separate layer. This way, the service remains completely in dark about how the low-level operations to access the database is done. This is known as the principle of Separation of Logic.
It is a good way, but at least one improvement can be done using generics:
public interface DAO<T> {
public void addItem(T item);
public void updateItem(T item);
public void removeItem(T item);
public T getItem(int id);
public List<T> getAll();
}
So now you will not need any casting. But anyway, you must make sure that all the DAOs will at least have those methods. Otherwise that will lead to more complexities. Moreover, if there are some DAOs that will have just exactly those methods, you will end up with pretty much compact clean code, e.g.:
public interface UserDAO extends DAO<User> {
// And that is basically it :)
}
public class UserDAOImpl implements UserDAO {
// Your implementations here
// ...
}
Note: I have replaced the Object[]
with List<T>
and not T[]
as you cannot do that in case of generics. But that is not a cons, it is better to use built-in containers.
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