Must Dependency Injection come at the expense of Encapsulation?

后端 未结 21 2425
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 05:21

If I understand correctly, the typical mechanism for Dependency Injection is to inject either through a class\' constructor or through a public property (member) of the clas

21条回答
  •  情歌与酒
    2020-12-04 05:59

    This exposes the dependency being injected and violates the OOP principle of encapsulation.

    Well, frankly speaking, everything violates encapsulation. :) It's a kind of a tender principle that must be treated well.

    So, what violates encapsulation?

    Inheritance does.

    "Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation'". (Gang of Four 1995:19)

    Aspect-oriented programming does. For example, you register onMethodCall() callback and that gives you a great opportunity to inject code to the normal method evaluation, adding strange side-effects etc.

    Friend declaration in C++ does.

    Class extention in Ruby does. Just redefine a string method somewhere after a string class was fully defined.

    Well, a lot of stuff does.

    Encapsulation is a good and important principle. But not the only one.

    switch (principle)
    {
          case encapsulation:
               if (there_is_a_reason)
          break!
    }
    

提交回复
热议问题