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.
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.
There are lots of arguments in favour of interfaces, see Google.
I can added to the points other people mentioned:
In short, it is just good to have interfaces!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With