Dalton
Dalton

Reputation: 420

Basic Generic DAO based on Reflection

Well, there's something bugging me in my project. I have lots and lots of hibernate entity classes and each one of them have their own DAO (inherited from a GenericDAO). Most of them have no specific funtion, being just an empty class inheriting GenericDAO.

Since I believe that those were unnecessary classes, I decided to get rid of them using reflection. After some coding, my call on all of those classes that have no specific methods apart from GenericDAO follow this design:

DAO.forClass(MyClass.class, MyClassPK.class).genericDAOMethod();

It works like a charm. I'm now rid of empty DAOs. But after searching through internet, I have found low to no solution like mine, so the question is:

is this approach wrong or bad in any considerable way? Why no one ever consider doing something like this?

Upvotes: 1

Views: 964

Answers (1)

Keith Enlow
Keith Enlow

Reputation: 914

Reflection is almost never considered the answer to a problem. Its just hard to read because a lot of people don't know what it is and people that come behind you to modify your code cannot understand it easily. Its not "self-documenting" to use a term from the book Code Complete.

Reflection is powerful, as you just found out doing it to implement a DAO. But you should just be weary of it. A term we use around my office is "code stink", which is code that might be there for specific purpose, but shouldn't be used everywhere unless absolutely needed. Make sure to documented properly so that people that do actually come behind you will know what the heck it is.

I like to use it to write jUnit tests in Spring to compare two objects from two different databases using reflection. But that's a test and isn't actually in production code.

Hope this helps and is kind of what you are looking for!

Upvotes: 5

Related Questions