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

前端 未结 2 533
予麋鹿
予麋鹿 2021-01-13 08:40

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 a

相关标签:
2条回答
  • 2021-01-13 09:17

    If you call out to your dependencies, you're actually doing work in a constructor.

    From a client's perspective that is unexpected. When I do something like this:

    var myObj = new SomeClass();
    

    I don't expect any side-effects.

    If you do things in the constructor, for example it could throw an exception, which is certainly not what you expect. It's like naming a method FetchUsers and inside that method creating a user and returning it. Not what you'd expect.

    0 讨论(0)
  • 2021-01-13 09:39

    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.

    0 讨论(0)
提交回复
热议问题