0

Since DO and IOC became well known and used ive seen a trend of an increase of using interfaces for lots of classes even if those classes are not services resolves by D/IOC. Like it would be better to at least have an interface of the class EVEN when the class itself is often referenced instead of the interface. What is the benefit of using interfaces like this if there is no DI/IOC.

Daarwin
  • 2,896
  • 7
  • 39
  • 69
  • It would be better if you can post some code. – Nghia Bui May 03 '19 at 07:22
  • 1
    If you only have 1 implementation of the concept, and only ever plan to have 1, then there's no need to use interfaces. Most DI containers these days allow class registration as well as interface registration, so even if you do decide to IoC it all, you can still skip the interface. If, however, you plan to have many ways of skinning this cat, you might want to make iCatSkinner so they can all be treated as the same thing. – Davesoft May 03 '19 at 08:03
  • 1
    Not only for DI, but also for testing it makes sense to use Interfaces. We use lots of interfaces for classes we need to mock. – Marc May 03 '19 at 08:29
  • Possible duplicate of [Java Interfaces Methodology: Should every class implement an interface?](https://stackoverflow.com/questions/2659366/java-interfaces-methodology-should-every-class-implement-an-interface) – jaco0646 May 05 '19 at 22:37

2 Answers2

4

Questions like this don't always have the same answer. There are many good reasons to make an interface, but there are also an a lot of interfaces that get made for no good reason.

Generally, interfaces are used as argument types to declare what a constructor or method needs, because a constructor or method that requires specific implementations in its arguments can be used in far fewer contexts.

This is an important consideration for non-private methods and constructors, which is why the use of interfaces is so pervasive. It covers a lot more use cases than just DI.

But if you are creating an implementation class that doesn't need to be passed to any such method or constructor, then there is no reason to make an interface. Every class or interface should have a purpose... and "to be the interface for this class" is not a valid purpose.

The purpose of an interface is to capture the requirements of its consumers, not its implementations.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
1

For me, an interface is above all the way to decouple code. It does not matter if you use IOC or not. Even using an interface with a single implementation is a good thing. For the evolution of an application, it's better to use interfaces that we can reimplement for our new needs or changes that we want to make.

This article describe better than me my opinion : Decouple your code

Emilien Mathieu
  • 301
  • 3
  • 16