Kilokahn
Kilokahn

Reputation: 2311

Need for separate interface and impl for DAO

We have a typical n-tier java application, and I noticed that our data access layers has DAO's that are of the type FooDAO and FooDAOImpl. I was looking to justify the need for the two and here is my analysis.

  1. If you had multiple implementation for the same interface, the abstraction is helpful. But given that we have already made the choice of the framework to be used for the DAOImpl (say iBATIS), is it really required?
  2. Help in proxying via Spring. From what I gather, classes that have interfaces can be proxied easily (going the JdkProxy route) rather than classes that have no interfaces (where the cglib route is chosen) and one has the subclass the class to be proxied. Subclassing has its problems where the class to proxied is final or has none default constructors - both of which are highly unlikely at the data access layer. Performance used to be a factor, but from what I hear, it is no longer a cause of concern.
  3. Help in mocking. Classes with interfaces are more suited to be mocked by mocking frameworks. I have only heard this, but not seen it in practice - so can't really count on it, but maybe because of the same factors as mentioned in #2 above.

With these points, I don't feel the real need for a separate FooDAO and FooDAOImpl where a simple FooDAO should suffice. Feel free to correct any of the points that I have mentioned.

Thanks in advance!

Upvotes: 8

Views: 1755

Answers (3)

Rogério
Rogério

Reputation: 16380

I would say that having a FooDAO interface with a single implementation FooDAOImpl is generally an anti-pattern. The simpler solution (no separate interfaces for DAOs) is much preferable, unless you have a solid reason otherwise - which doesn't seem to be the case here.

Personally, I would go even further and say that having DAOs at all is not the best choice. I prefer having a single persistence facade class implemented on top of an ORM API such as Hibernate or JPA. Maybe iBATIS is too low-level for that, though.

Upvotes: 0

Kilokahn
Kilokahn

Reputation: 2311

I tried #3 with Mockito and it was able to mock POJO's without interfaces just fine. With the arguments mentioned against #1 and #2, I am inclined not to go with separate DAO and DAOImpl for now. Feel free to add other points of comparison.

Upvotes: 2

Rainer Schwarze
Rainer Schwarze

Reputation: 4745

I see a fourth reason:

  • Hide implementation details

Depending for instance on the team, the expected lifetime of the software or the amount of change anticipated in the future, it pays to hide as much as possible even if there is only one implementation.

Upvotes: 1

Related Questions