I have a project where I have two classes that both require a database access object that updates the same table. The constraints of the framework and project make it so that I cannot combine these two classes. I have created a case below that shows how the setup is. Class A needs to be able to update and read the record, while class B needs to be able to update and delete the record.
If I use the classes as they are, it works just fine, but I am having a problem with that fact that each of the classes is requiring functionality that it is not using to be implemented. For example, in order to use class A, I have to pass it a dao that implements the delete function, even though it will never be called. Similarly, I have to pass class B a dao that implements the read function but it will never be called.
I thought about approaching it by having interfaces that inherit others (IReadDao, IUpdateDao, IDeleteDao being the daos that would be inherited from), but this approach would basically require a different interface for each combination of functions (IUpdateAndRead, IReadAndDelete, IReadAndUpdate ...)
I want to use an interface for the dao because I don't want to couple the application with the database. Is there a pattern or method for accomplishing what I want that anybody knows about? Thanks in advance.
class IDao {
void update(ModelDao model);
void delete(String guid);
ModelDao read(String guid);
}
Class A {
private IDao dao;
public A(IDao dao) {
this.dao = dao;
}
public void doStuff() {
ModelDao model = new ModelDao();
...
dao.update(model);
}
public void readThenDoSomething(String id) {
ModelDao model = dao.read(id);
...
}
}
Class B {
private IDao dao;
public B(IDao dao) {
this.dao = dao;
}
public void makeUpdate() {
ModelDao model = new ModelDao();
...
dao.update(model);
}
public void delete(String id) {
dao.delete(id);
}
}
I
fromSOLID
). Might want to read a bit on it.