Must Dependency Injection come at the expense of Encapsulation?

后端 未结 21 2463
被撕碎了的回忆
被撕碎了的回忆 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:41

    Yes, DI violates encapsulation (also known as "information hiding").

    But the real problem comes when developers use it as an excuse to violate the KISS (Keep It Short and Simple) and YAGNI (You Ain't Gonna Need It) principles.

    Personally, I prefer simple and effective solutions. I mostly use the "new" operator to instantiate stateful dependencies whenever and wherever they are needed. It is simple, well encapsulated, easy to understand, and easy to test. So, why not?

提交回复
热议问题