I always wonder what is the motivation when people do interfaces with
just one implementation.
I mean, using this logic, every single function can be hidden behind an
interface. Even the sole implementation of the interface can be hidden
behind a yet another interface.
If there's just one implementation, then the interface is not necessary!
An interface, esp. when returned from a method, is the best way the define a limited contract. If you return the concrete class, you have the following potential issues:
- Very broad, unspecific contract that may even obscure the methods purpose
- You cannot modify the contract without modifying the class AND vice versa
- Shrinking a contract (taking away elements) is far harder and more likely to cause breakages in other code than growing a contract
- Mocks become more cumbersome because the contract is so broad
- Changes to the concrete class cause ripple effects in code that doesn't care about the change
I think you've navigated away from the scope of my remark; I've
specifically asked what's the point of using interfaces when there's
just one implementation, not "what is the point of interfaces" in
general.
One motivation is to separate interface and implementation. Using interface allows one to easily observe available methods in a one place. With class, one must use IDEs to filter out hundreds irrelevant lines just to find out class contract. If you ever used Delphi or C++, it provides much better experience by clearly separating class interface and class implementation.
I mean, using this logic, every single function can be hidden behind an interface. Even the sole implementation of the interface can be hidden behind a yet another interface.
If there's just one implementation, then the interface is not necessary!