Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's a good question - but at some point, encapsulation in its purest form <em>needs</em> to be violated if the object is ever to have its dependency fulfilled. Some provider of the dependency <strong>must</strong> know both that the object in question requires a <code>Foo</code>, and the provider has to have a way of providing the <code>Foo</code> to the object.</p> <p>Classically this latter case is handled as you say, through constructor arguments or setter methods. However, this is not necessarily true - I know that the latest versions of the Spring DI framework in Java, for example, let you annotate private fields (e.g. with <code>@Autowired</code>) and the dependency will be set via reflection without you needing to expose the dependency through any of the classes public methods/constructors. This might be the kind of solution you were looking for.</p> <p>That said, I don't think that constructor injection is much of a problem, either. I've always felt that objects should be fully valid after construction, such that anything they need in order to perform their role (i.e. be in a valid state) should be supplied through the constructor anyway. If you have an object that requires a collaborator to work, it seems fine to me that the constructor publically advertises this requirement and ensures it is fulfilled when a new instance of the class is created.</p> <p>Ideally when dealing with objects, you interact with them through an interface anyway, and the more you do this (and have dependencies wired through DI), the less you actually have to deal with constructors yourself. In the ideal situation, your code doesn't deal with or even ever create concrete instances of classes; so it just gets given an <code>IFoo</code> through DI, without worrying about what the constructor of <code>FooImpl</code> indicates it needs to do its job, and in fact without even being aware of <code>FooImpl</code>'s existance. From this point of view, the encapsulation is perfect.</p> <p>This is an opinion of course, but to my mind DI doesn't necessarily violate encapsulation and in fact can help it by centralising all of the necessary knowledge of internals into one place. Not only is this a good thing in itself, but even better this place is outside your own codebase, so none of the code you write needs to know about classes' dependencies.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload