In this example we will see why you should not declare interface for service and then implement it.
Generaly service composition is a bad idea because:
- Services are generaly effectfull, but effects are not part of their methods' signatures, so it's hard to predict what would happen if you call it;
- Composing services can lead to circular dependencies, which are resolvable only in runtime(happens more often than you think).
Now to declaring interfaces itself. Primary reason why we create interfaces is dependency inversion, we want to change the direction of dependency to decrease coupling. In this example we want to invert dependency from ServiceBImpl to ServiceA. Let's see what happens when we introduce interface ServiceA:
ServiceA
contains ALL methods ofServiceAImpl
. Any change toServiceAImpl
contract will be reflected inServiceA
and vice versa.- ServiceBImpl uses ONLY doFoo method of ServiceA. But if we want to mock it we have to mock two more unused method.