Using Interfaces to Write DAO Classes

I am creating a new web application that will use a bunch of data access classes (DAOs) to perform CRUD operations on data. I know that I have to 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 write interfaces? I will inject DAO classes into the Spring controller (I use Spring MVC classes) using spring.

+4
source share
6 answers

NOTE: You should always try to separate the interface from the implementation. This will give you more control over other layers using this DAO layer.

But, as you know, the interface gives you more abstraction and makes the code more flexible and resistant to changes, since you can use different implementations of the same interface without changing its client. However, if you do not think your code will change, or (especially), if you think that your abstraction is good enough, you do not have to use interfaces

In other words: interfaces are good, but before creating an interface for each class, think about it

+9
source

Yes you need. Your classes that use them should rely only on interfaces. This makes it easy to initialize client classes with fake implementations of your DAOs, to, among other things, test these classes. If you just use a specific class, then the clients of your DAOs will directly depend on this single (database access) implementation and will be very difficult to test.

The simplicity of creating classes depends only on the interfaces for the services on which they depend, is one of the main advantages of dependency injection, and you will make yourself and your application bad without using it.

+8
source

The biggest reason you should write interfaces for your DAO (Warehouses?) Is that you can easily create mocks (or use a mocking structure) for unit test of everything that has a dependency on DAO.

Even if you don't do unit testing, it's still good design practice to follow DIP

Also, how long does a right-click => extract interface really take inside any modern development environment?

+3
source

I do not agree with Color Blend. Basically, my opinion is: everything that is entered using spring should be supported (and specified) by the interface.

+2
source

The general approach in developing APIs for external clients is to create interfaces, not classes.

Thus, the client will only know about the API contract, which must be explicitly specified in the javadocs interface, and there will be no dependence on the implementation details that you choose.

In addition, you can test your API clients in JUnit by providing mock implementations of your API, which would be more difficult if you are not using interfaces.

+2
source

I do not think you need. You just burn your time. Create them only if necessary.

0
source

Source: https://habr.com/ru/post/1332963/


All Articles