Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Duplicate code in many DAO classes

 
Swerrgy Smith
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 2756
32
Eclipse IDE Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 1203
25
Android C++ Java Linux PHP Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 2756
32
Eclipse IDE Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much. Can anyone give me an example of using AOP in this problem?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic