Hi all,
So, as my first post on Javaranch, I wanted to ask a question about using Generics. I know that what I've done below works, but is it "proper"? Are there hidden pitfalls that I'm not seeing?
I've been stuck in the
java 1.4 world for quite a while, and in the past year finally have been able to break out and try out some of the new stuff in JDK5 and 6. I've been developing an application that is using Hibernate, Spring and Struts2. When developing our DAOs, I saw that all of our methods are basically identical (insert, delete, update, etc), except the only difference is that the Domain object that we are passing in is different. So, I thought - Generics! So, I basically did the following:
I created an Interface called GenericDAO:
And then created another Interface that extends from GenericDAO (to be used in my Action classes for the dependency injection):
So, at this point, I have a CourseDAO interface that I can use in any of my actions that require access to it. However, I still needed a concrete implementation of this. And because I knew that the concrete implementations when using Hibernate would be identical (except for the Domain object), I created a concrete implementation of GenericDAO, with Generics:
(the find takes in a Class<E> object because we found that you can't do "E.class".. If anybody knows a way around this, please let me know me!)
Then, finally - I created my concrete HibernateCourseDAO class:
Now, I look at that and think its either a great way of using Generics, or completely misusing the concepts. I've had a few discussions with co-workers about it, and we can't really come to a conclusion. The real sticking point is that the
HibernateGenericDAO implements
GenericDAO, and then,
HibernateCourseDAO not only extends from
HibernateGenericDAO but also implements
CourseDAO (which extends from
GenericDAO), and that just feels kind of... redundant. I justify it to myself that it means we can still use the CourseDAO interface in the Action, and gives us the flexibility to use a mock of CourseDAO in
testing. So, back to the original question - is this a proper way of using Generics?
Thanks,
Dan Slack
Langui Systems Inc.