General J2EE: DAO doubts
A very basic design question -
One of my colleagues recently told me that only interfaces have to be exposed to the client.But my counter is that since we can control thro' access modifiers, the parts which we need to expose/hide from the client, why should an interface be used at all.
Like, for example, if we look at the DAO pattern as described in J2EE blueprints
it advocates the use of interfaces like CustomerDAO,AccountDAO even if there is only one datasource.(If there are several then it makes sense as in CloudscapeCustomerDAO,OracleCustomerDAO).
Also if there is a single persistent store then why is there a need for the DAOFactory? If I am 100% sure that there will be only one datasource then can i directly instantiate(new DAO()) in my stateless session bean.Please let me know if it is ok to do that since I do not want to go through the rigmarole of creating lots of interfaces without any good reason.
Please let me know if it is ok to do that since I do not want to go through the rigmarole of creating lots of interfaces without any good reason.I agree with your colleague, all the examples you give deserve an interface. Even the DAO example where you know you will have one persistent store. Let's say tou know you will be going with Oracle-8i. What if in the future you want to migrate to Oracle-14h, or the sort. Interfaces add good value and add little complexity to a system. I would even argue that done right an interface makes a system easier to use.
There are many other things that an interface gives you. One such tool is the ability to decorate.
Also frameworks like spring let you fully leverage an interface with it's inversion of controll container.
Thanks Matthew, I am convinced about the generic utility of interfaces.But I am having one more issue with DAO interfaces here.
The problem is as follows.
In some cases I would like to group several DAO operations(say WorkFlowDAO,ConfHallBookingDAO) into one transaction.So the transaction demarcation has to be outside the DAO,say in my stateless session bean.
But also i might require the same operations as individual transactions also.
So this can be resolved by having WorkFlowDAO interface and WorkFlowDAOImpl and WorkFlowDAOImplJTA classes.But the issue here is that i have to repeat quite a lot of code in both the DAO classes,which,of course,cannot be put in the parent interface.So would it make more sense to have WorkFlowDAO as an abstract class containing the common code with WorkFlowDAOImpl(1)...WorkFlowDAOImpl(n) extending WorkFlowDAO.While the J2EE core pattern advocates the use of only interfaces it falls short of providing a solution for placing this common code.
You can instantiate the Datasource now directly, the issue comes when you change the Datasource in future. Then you have to change your entire code. If it is an interface, the client does not change the code, the only change is in the implementation.