0

Why loose coupling under java code?
i don't understand, be loose coupling when using interface
why using interface?

Service.java

interface Service{
    public void method();
}

in ServiceImpl.java

@Override
ServiceImpl implements Service{
    public void method(){
        //To-do override
    }
}
  • https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface and https://softwareengineering.stackexchange.com/questions/150045/what-is-the-point-of-having-every-service-class-have-an-interface – Nikolas Charalambidis May 26 '20 at 08:53
  • @Nikolas Thanks you're comment i will try read two links, Thanks a lot – Kotlin Ken May 26 '20 at 09:04

1 Answers1

0

When you program to the interface you usually inject that interface in other classes, when calling methods you then call the methods on the interface and not the actual implementation. Thus, when you want to switch the implementation it is as simple as replacing your @Bean method in your Configuration class with the new implementation.

Imagine you don't do this and want to change the implementation. You would need to find all occurences in your codebase and replace it with the new implementation.

Other advantages of coding to the interface include increased testability, since you can mock your dependencies, allows for the use of JDK dynamic proxy and increased cohesion between your classes.

Daniel Jacob
  • 1,455
  • 9
  • 17
  • actually already know theory, i can draw some Benefits But... when coding spring mvc pattern one service call one repository, is this necessary interface implementation? – Kotlin Ken May 26 '20 at 09:08
  • IMHO I would say yes, because you think at this point you are calling one repository, but this may change, then you need to change your whole codebase. Imagine in the future you want to change your service to get certain data from a relational database but other data from a non-relational (i.e. NOSQL) datastore. Also as I have mentioned the increased testability is of importance. If you don't code to the interface you cannot mock the repository and this would make testing your service harder. – Daniel Jacob May 26 '20 at 09:13
  • thanks you'r mentions, understand little bit, and summarize you'r comments need interface because under two reason right? 1. when code change need more pay 2. can't mock – Kotlin Ken May 26 '20 at 09:22
  • There are also other advantages, for example it enables the use of a proxy provided by the JDK. When you add certain annotations, like @Transactional for example, Spring intercepts the call and wraps your code around code for transaction management thereby enhancing your code with functionality that you did not write yourself. – Daniel Jacob May 26 '20 at 09:28