3

First off, I have done some reading and I am wondering what is the purpose of having a Interface and the implementation class for example the Data Access Objects (DAO)? I have read that it increases flexibility, but I was wondering if someone could provide a concrete example as to why we need an interface.

If we are autowiring, do we still need to use a Interface and Implementation that implement the interface? If so, why? Do we just need the impl?

Thank you in advance.

Xstian
  • 8,184
  • 10
  • 42
  • 72
Alan
  • 9,331
  • 14
  • 52
  • 97
  • @NathanHughes can Spring Data call SQL Package stored procedures? I am still wondering what the purpose of having an interface is for. So far it seems just like extra code to me. – Alan Nov 05 '14 at 15:05
  • yes, with JPA and JPQL. http://stackoverflow.com/q/3572626/217324 – Nathan Hughes Nov 05 '14 at 15:07
  • When you define an interface for your classes (maybe also for a DAO), it helps with dependency injection. If you want to inject another class that offers "equivalent" functionality, using an interface really helps. You could have a DAO for different frameworks or different repository DB, and you could choose how inject. @Nathan Hughes right, Spring Data provides the impl for you, but you can provide some implementation if you deemed necessary. – Xstian Nov 05 '14 at 15:08
  • @Xstian: yes, i was overgeneralizing. you can provide your own custom impl. i haven't run into a case where i've had to do that yet, fortunately. – Nathan Hughes Nov 05 '14 at 15:09
  • Alan, you have a point. @Autowired is really the antithesis of IOC and dependency injection as it locks you into a concrete implementation. Then why the interface? I'm with you in wondering at its applicability; you don't have to have an interface, you can Autowire an implemented class. Unless the interface is useful in some other capacity why do we use it? – BillFromHawaii Nov 05 '14 at 19:32

1 Answers1

1

You don't strictly need an interface. But there are two reasons to prefer them:

  • You can easily swap the implementation for testing purposes
  • Proxy-ing beans for the purposes of aspect oriented programming or similar is easier (Java supports it out of the box)

Other reasons might be added, but these are the main 2 in my opinion. Still, don't feel forced to work like that. If the case you're working on does not warrant this flexibility, there's no need to complicate things.

And, by all means, never call your classes *Impl. If you can not come up with a proper name for the implementation, it means you shouldn't be having an interface to begin with.

kaqqao
  • 12,984
  • 10
  • 64
  • 118