Hacker News new | past | comments | ask | show | jobs | submit login

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


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.


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 always wonder what is the motivation when people do interfaces with just one implementation.

They intend to write a test double which implements the interface. But then they don't get around to writing tests?




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: