Must Dependency Injection come at the expense of Encapsulation?

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

    As Jeff Sternal pointed out in a comment to the question, the answer is entirely dependent on how you define encapsulation.

    There seem to be two main camps of what encapsulation means:

    1. Everything related to the object is a method on an object. So, a File object may have methods to Save, Print, Display, ModifyText, etc.
    2. An object is its own little world, and does not depend on outside behavior.

    These two definitions are in direct contradiction to each other. If a File object can print itself, it will depend heavily on the printer's behavior. On the other hand, if it merely knows about something that can print for it (an IFilePrinter or some such interface), then the File object doesn't have to know anything about printing, and so working with it will bring less dependencies into the object.

    So, dependency injection will break encapsulation if you use the first definition. But, frankly I don't know if I like the first definition - it clearly doesn't scale (if it did, MS Word would be one big class).

    On the other hand, dependency injection is nearly mandatory if you're using the second definition of encapsulation.

提交回复
热议问题