JHeni
JHeni

Reputation: 751

Why should one inject concrete classes opposed to injecting interfaces

I'm currently working on a Java project. I'm quite new to Java. I have done C++/C# in the past.

I have a question regarding dependency injection. The basic idea why to use it is already clear to me.

public class MyClass
{
  @Inject
  private IFoo fooInterface;

  @Inject
  private Bar barClass;
  
}

with

public interface iFoo
{
}

public class Bar
{
}

Now it makes perfectly sense to inject an actual interface implementation to reduce dependencies.

But why would I like to inject a "normal" class with does not implement an interface?

Could you help me understand?

Edit: Thank you guys for all your comments. I believe I'm getting now the idea behind dependency injection.

Just to clarify: After speaking to the other devs I was told that in our project all injected dependencies are constructed at startup. However not all member objects are already known at startup time. Therefore these members objects can't be passed via constructor.

Another point is that, for each class type (for ex. Bar) only 1 instance seams to be constructed for the whole project, this instance will be passed around in the whole project and accessed by multiple threads. Therefore we might run into concurrency issues if we use member variables.

=>the conclusion in our team was to avoid member variables and pass all arguments as function arguments.

=>Now I'm searching for a way to have DI (which makes perfectly sense) but also to have members variables.

Upvotes: 0

Views: 822

Answers (1)

ruediste
ruediste

Reputation: 2949

When using dependency injection, a class delegates the responsibility to create it's dependencies to the dependency injection system. So you never want to instantiate a dependency yourself.

Otherwise, if your Bar class needs dependencies, you'd have to take care of them as well in MyClass. And if you use Bar in many places and add a dependency to it, you'd have to change all those usages of Bar as well.

Upvotes: 1

Related Questions