Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shouldn't I call my dependencies from within the constructor?

I've long considered it a bad practice to call out to a classes dependencies from within the constructor but wasn't able to articulate why to a colleague yesterday. Can anyone provide a good reason for NOT doing this?

like image 748
skb Avatar asked Mar 07 '14 18:03

skb


People also ask

Is it difficult to inject dependency by constructor?

Frameworks that apply the Constrained Construction anti-pattern can make using Constructor Injection difficult. The main disadvantage to Constructor Injection is that if the class you're building is called by your current application framework, you might need to customize that framework to support it.

What is dependency injection and how is it used in a constructor?

Constructor injection The most common form of dependency injection is for a class to request its dependencies through its constructor. This ensures the client is always in a valid state, since it cannot be instantiated without its necessary dependencies.

Which one is better constructor injection or setter injection?

Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring we use XML files, readability is a much bigger concern.


1 Answers

There are several reasons for Nikola Malovic's 4th law of IoC:

  • When we compose applications with Constructor Injection we often create substantial object graphs, and we want to be able to create these graphs as efficiently as possible. This is Nikola's original argument.
  • In the odd (and not recommended) cases where you have circular dependencies, the injected dependencies may not yet be fully initialized, so an attempt to invoke their members at that time may result in an exception. This issue is similar to the issue of invoking virtual members from the constructor. Conceptually, an injected dependency is equivalent to a virtual member.
  • With Constructor Injection, the constructor's responsibility is to demand and receive the dependencies. Thus, according to the Single Responsibility Principle (SRP), it should not try to do something else as well. Some readers might argue that I'm misusing the SRP here, but I think I'm simply applying the underlying principle in a more granular context.

Please notice that this rule is contextual: it applies to Services that use Constructor Injection. Entities and Value Objects tend not to use DI, so their constructors are covered by other rules.

like image 148
Mark Seemann Avatar answered Sep 21 '22 23:09

Mark Seemann