问题
I'm creating a new web application which will use a bunch of Data Access Object(DAO) classes for doing CRUD operations on the data. I know I should write java interfaces when I have external users/applications using my DAO classes. But if there is no such need do you think I should still write the interfaces? I'll be injecting DAO classes in to the Spring Controller(I'm using Spring MVC) classes using spring.
回答1:
NOTE THAT : You should always try to separating the Interface from the Implementation. This will give you more control to the other layers, using this DAO layer.
But, As you know an interface gives you more abstraction, and makes the code more flexible and resilient to changes, because you can use different implementations of the same interface without changing its client. Still, if you don't think your code will change, or (specially) if you think your abstraction is good enough, you don't necessarily have to use interfaces
In other words: interfaces are good, but before making an interface for every class think about it
回答2:
Yes, you should. Your classes that use them should rely on the interfaces only. This enables you to easily initialize the client classes with fake implementations of your DAOs in order to test those classes, among other things. If you just use a concrete class, then the clients of your DAOs will depend directly on that single (database accessing) implementation and be very difficult to test.
The ease of making classes rely only on interfaces for services they depend on is one of the main strengths of dependency injection and you'd be doing yourself and your application a disservice by not taking advantage of it.
回答3:
The biggest reason you should write interfaces for your DAO's (Repositories?) is so that you can easily build mocks (or use a mocking framework) to unit test anything which has a dependency ON the DAO.
Even if you're not doing unit testing, it is still a good design practice to follow DIP
Besides, how long does it really take to "right click=>Extract interface" inside of any modern IDE?
回答4:
I disagree with Colour Blend. Basically my opinion is: anything that gets injected by spring should be backed (and referenced) by an interface.
回答5:
Common approach when designing API for external clients is to create interfaces, not classes.
This way client will know only about contract of API which should be explicitly stated in interface javadocs and there will be no dependency on implementation details you choose.
Plus, you will be able to test clients of your API in JUnit, by providing mock implementations of your API, which would be harder if you not using interfaces.
回答6:
I don't think you should. You'll just burn up your time. Create them only if it is necessary.
来源:https://stackoverflow.com/questions/4504014/using-interfaces-for-writing-dao-classes