Hacker News new | ask | show | jobs
by LinXitoW 590 days ago
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

2 comments

The problem is that all the items you've listed are basically "just in case we'll need to do something later".

And this basically never happens, but you still have to carry that extra overhead of interfaces.

Java also supports private/public method visibility, and this can be used to clearly show the contract. No need for interfaces.

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.
I think parent means that the one implementation may be changed in the future, so everything applies.

If you 100% sure the one implementation will never change, then I'd say you're right. But it requires future-telling.