Hacker News new | ask | show | jobs
by VladRussian 5301 days ago
> In code review if you have an interface and only one implementation I'd make you remove the interface

which changes the contract from "this component will accept and work with anything implementing this interface" to "this component will accept and work with anything of this class or inheriting from this class". And without multiple inheritance ... Do you feel the difference?

1 comments

If there is only one implementation of an Interface, "anything implementing this Interface" and "anything of this class" are the same thing.

Coding to an interface is a good thing - but it's the concept "interface", not necessarily the language feature named "Interface" that's important. If/when you have multiple concrete objects which share the same interface, it's trivial there to switch references from the concrete type to that of the Interface (you were coding to a conceptual interface representing a consistent abstraction of a single responsibility in the beginning so your Interface is interchangeable, correct?)

But you understand interfaces, you have just given an explanation. The candidates I interviewed didn't explain themselves at all, I think if a language has a feature you should be able to explain when and when not to use it.

I think that all Java IDEs make it trivial to introduce an interface when it is required, so unless you are producing an API for consumption by a third party you should only introduce an interface when you have multiple implementations, or a third party can legitimately produce their own implementation, and not because you think you may have multiple implementations at sometime in the future.

Also if you have a single implementation naming it InterfaceImpl is just lazy, you almost always have more information that you can use to name it, it might be a InterfaceUsingJdbc or an InterfaceFileBased for example.

> If/when you have multiple concrete objects which share the same interface, it's trivial there to switch references from the concrete type to that of the Interface

you're a lucky person that it has been trivial for you, your teammates and all the known and unknown clients of your code and components. I can only envy your experience.

Lots of Java development is carried out for internal business applications and like it or not they would typically be integrated with third parties using something like SOAP or a shared database. So in this type of application the choice of a concrete class over an interface probably has little impact on the known or unknown clients of your code.

However, as you point out, if you are presenting a Java API to your known and unknown clients you had better think carefully about which abstractions you are going to expose and interfaces are probably going to be very helpful.