Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service and DAO always implement interfaces

In all the MVC projects I've seen, "service" and "DAO" classes always implemented their own interfaces. But almost all the times, I haven't seen a situation in which having this interface has been useful.

Is there any reason to use interfaces in these cases? What may be the consequence of not using interfaces in "service" and "DAO" classes? I can't imagine any consequences.

like image 745
user1883212 Avatar asked Aug 27 '13 23:08

user1883212


2 Answers

Spring is an Inversion of Control container. This, in one sense, means that the implementation of classes you use doesn't fall on the application but on its configuration. If you have a class that needs a UserRepository to store User instances, it'd be something like

class UserService {
    @Autowired
    private UserRepository userRepository;
}

interface UserRepository {
    List<User> getUsers();
    User findUserBySIN(String SIN);
    List<User> getUsersInCountry(Long couyntryId);
}

And you would have a bean declared for it

<bean class="com.myapp.UserRepositoryHibernateImpl">
   ...
</bean>

Notice this bean is UserRepositoryHibernateImpl which would implement UserRepository.

At some point in the future of the world, the Hibernate project stops being supported and you really need a feature that is only available on Mybatis so you need to change implementations. Because your UserService class is using a UserRepository declared with the interface type, only the methods visible on the interface are visible to the class. So changing the actual polymorphic type of userRepository doesn't affect the rest of the client code. All you need to change (excluding creating the new class) is

<bean class="com.myapp.future.UserRepositoryMyBatisImpl">
   ...
</bean>

and your application still works.

like image 196
Sotirios Delimanolis Avatar answered Sep 19 '22 14:09

Sotirios Delimanolis


There are lots of arguments in favour of interfaces, see Google.

I can added to the points other people mentioned:

  1. Imagine you change your DAO implementations from Hibernate to iBatis. Dependency to interface rather than implementation would be a great help for the service layer.
  2. If you use AOP or proxies using JDK dynamic proxies then your classes must implement interfaces. This is not the case for CGLIB.
  3. In the service layer if you want to release your methods to other clients to call, giving them "interface as a contract" would make more sense rather than implementations.
  4. If you ever want to separate services.jar from daos.jar then having interfaces on your daos would save the services.jar from recompile in case daos.jar changes.

In short, it is just good to have interfaces!

like image 30
reza Avatar answered Sep 22 '22 14:09

reza