Should you always Code To Interfaces In Java [closed]

In general I agree with the other answers: use an interface when you know or anticipate change and/or different implementation, or go for testability.

But it’s not always easy to know in advance what may change in the future, especially if you are not so experienced. I think the solution for that problem is refactoring: keep it simple (= no interface) as long as it is not needed. When the need arises simply do an “Introduce/Extract interface” refactoring (supported by almost all decent IDEs).

When you do it extract only those methods that are actually needed by the callers. Don’t be afraid to extract more then one separate interfaces (if not all of the extracted methods are really coherent).

One driver of the refactoring might be the testing: if you can’t easily test something with classes only consider introducing one/some interface(s). This will also allow you to use mocking which may greatly simplify testing in many cases.

Edit: based on Tarski’s comment I’ve realized one more important scenario/adjustment to the previous statements:
If you provide an external API (for other [sub]projects, or really release it “to the wild”) then using interfaces in the API (except for simple value classes) is almost always a good idea.
It will allow you to change the impl if you like without disturbing the client code. You will have a problem only if you also have to change the interface. Not breaking compatibility will be very tricky (if not impossible).

Leave a Comment