aspose file tools*
The moose likes Object Relational Mapping and the fly likes Duplicate code in many DAO classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Duplicate code in many DAO classes" Watch "Duplicate code in many DAO classes" New topic
Author

Duplicate code in many DAO classes

Swerrgy Smith
Ranch Hand

Joined: Mar 26, 2010
Posts: 91
Hi all,

Suppose I have many DAO classes like this:



The only difference among these DAO classes are the method parameter (Employee, Person, Animal ...).

How can I reduce duplicate code in this case?

Thank you.
Jayesh A Lalwani
Bartender

Joined: Jan 17, 2008
Posts: 2393
    
  28

This is a common problem in DAO pattern. This is why AOP was invented. When you use DAO pattern, all of your DAO classes have boilerplate code. The way this problem is solved is by Weaving the boiler plate code into your code. So, basically, you will put a transaction annotation on your method, and your method won't need the boilerplate code to open and close the transaction. Your code only contains business logic. The framework will inject the boilerplate code into your code

Karthik Shiraly
Ranch Hand

Joined: Apr 04, 2009
Posts: 513
    
    6
Another solution is using a template helper like this, where the template does all the boilerplate initialization and cleanup, and invokes your DB logic inbetween:



It's not as elegant as AOP, but still reduces the boilerplate. This pattern is followed in Spring framework to help with both hibernate and JDBC operations. In recent versions, spring has deprecated them because they couple your code to spring framework,
but if you're writing your own templates, it's not a problem.
Jayesh A Lalwani
Bartender

Joined: Jan 17, 2008
Posts: 2393
    
  28

You could use a Proxy pattern too, which is what AOP uses internally. However, your DAOs will need to implement an interface.
Swerrgy Smith
Ranch Hand

Joined: Mar 26, 2010
Posts: 91
Thank you very much. Can anyone give me an example of using AOP in this problem?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Duplicate code in many DAO classes