146

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 class.

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

Am I correct in identifying this tradeoff? How do you deal with this issue?

Please also see my answer to my own question below.

urig
  • 16,016
  • 26
  • 115
  • 184
  • 9
    this is a very smart question imho – dfa Jun 17 '09 at 07:05
  • 5
    Answering this question first requires an argument about what *encapsulation* means. ;) – Jeff Sternal Mar 24 '10 at 13:59
  • 2
    Encapsulation is maintained by the interfaces. They expose the essential characteristics of the object and hide details such as dependencies. This allows us to 'open-up' the classes to some extent as to provide a more flexible configuration. – Lawrence Wagerfield Jul 13 '11 at 09:15
  • @JeffSternal why did you delete your answer? It was pretty accurate and straightforward, compared to some of the other most upvoted answers now. – Steven Liekens Apr 15 '21 at 22:04
  • 1
    Using DI will force constructor parameters and other classes to be made public. You shouldn't expose things to the outside world for the sake of using a DI framework. – IamDOM Dec 28 '21 at 09:39

21 Answers21

65

There is another way of looking at this issue that you might find interesting.

When we use IoC/dependency injection, we're not using OOP concepts. Admittedly we're using an OO language as the 'host', but the ideas behind IoC come from component-oriented software engineering, not OO.

Component software is all about managing dependencies - an example in common use is .NET's Assembly mechanism. Each assembly publishes the list of assemblies that it references, and this makes it much easier to pull together (and validate) the pieces needed for a running application.

By applying similar techniques in our OO programs via IoC, we aim to make programs easier to configure and maintain. Publishing dependencies (as constructor parameters or whatever) is a key part of this. Encapsulation doesn't really apply, as in the component/service oriented world, there is no 'implementation type' for details to leak from.

Unfortunately our languages don't currently segregate the fine-grained, object-oriented concepts from the coarser-grained component-oriented ones, so this is a distinction that you have to hold in your mind only :)

Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101
  • 22
    Encapsulation is not just a piece of fancy terminology. It is a real thing with real benefits, and it doesn't matter if you consider your program to be "component oriented" or "object oriented". Encapsulation is supposed to protect the state of your object/component/service/whatever from being changed in unexpected ways, and IoC does take away some of this protection, so there's definitely a tradeoff. – Ron Inbar Mar 31 '15 at 15:37
  • 2
    Arguments supplied through a constructor still fall within the realm of _expected_ ways in which the object may be "changed": they're explicitly exposed, and invariants around them are enforced. _Information hiding_ is the better term for the kind of privacy you're referring to, @RonInbar, and it's not necessarily always beneficial (it makes the pasta harder to untangle ;-)). – Nicholas Blumhardt Jul 29 '16 at 00:26
  • 2
    The whole point of OOP is that the pasta tangle is separated out into separate classes and that you only have to mess with it at all if it's the behaviour of that particular class you wish to modify (this is how OOP mitigates complexity). A class (or module) encapsulates its internals while exposing a convenient public interface (this is how OOP facilitates reuse). A class that exposes its dependencies via interfaces creates complexity for its clients and is less reusable as a result. It is also inherently more fragile. – Neutrino Oct 25 '17 at 19:11
  • An interface can be implemented by different types that behave in different ways, so an interface does not enforce constraints in the way that a concrete class does. By exposing its dependencies in such a way that they must be satisfied by interfaces, a class opens itself up to the possibility that an injected dependency behaves in an unexpected manner, opening up the potential for a whole class of runtime bugs that code with statically compiled dependencies does not suffer from. – Neutrino Oct 25 '17 at 19:13
  • 1
    No matter which way I look at it, it seems to me that DI seriously undermines some of the most valuable benefits of OOP, and I've yet to encounter a situation where I've actually found it used in a manner that solved a real existing problem. – Neutrino Oct 25 '17 at 19:13
  • 2
    Here's another way to frame the problem: imagine if .NET assemblies chose "encapsulation" and didn't declare which other assemblies they relied on. It would be a crazy situation, reading docs and just hoping that something works after loading it. Declaring dependencies at that level lets automated tooling deal with the large-scale composition of the app. You have to squint to see the analogy, but similar forces do apply at the component level. There are trade-offs, and YMMV as always :-) – Nicholas Blumhardt Oct 26 '17 at 00:56
30

It's a good question - but at some point, encapsulation in its purest form needs to be violated if the object is ever to have its dependency fulfilled. Some provider of the dependency must know both that the object in question requires a Foo, and the provider has to have a way of providing the Foo to the object.

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 @Autowired) 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.

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.

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 IFoo through DI, without worrying about what the constructor of FooImpl indicates it needs to do its job, and in fact without even being aware of FooImpl's existance. From this point of view, the encapsulation is perfect.

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.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
  • Thanks for the detailed reply :) Would you know of a DI framework for .net that allows for private members to be injected into? Might Spring.net support this? How significant might the impact on performance be, as this mechanism relies on reflection? – urig Jun 17 '09 at 16:45
  • 2
    Good points. I advise against using @Autowired on private fields; that makes the class hard to test; how do you then inject mocks or stubs? – lumpynose Jun 25 '09 at 20:10
  • 4
    I disagree. DI does violate encapsulation, and this can be avoided. For example, by using a ServiceLocator, which obviously does not need to know anything about the client class; it only needs to know about the implementations of the Foo dependency. But the best thing, in most cases, is to simply use the "new" operator. – Rogério Jul 21 '09 at 22:34
  • 6
    @Rogerio - Arguably any DI framework acts exactly like the ServiceLocator you describe; the client doesn't know anything specific about Foo implementations, and the DI tool doesn't know anything specific about the client. And using "new" is much worse for violating encapsulation, as you need to know not only the exact implementation class, but also the exact classes *and* instances of all the dependencies it needs. – Andrzej Doyle Jul 27 '09 at 11:29
  • 4
    Using "new" to instantiate a helper class, which often isn't even public, promotes encapsulation. The DI alternative would be to make the helper class public and add a public constructor or setter in the client class; both changes would break the encapsulation provided by the original helper class. – Rogério Jul 28 '09 at 22:46
  • 1
    "It's a good question - but at some point, encapsulation in its purest form needs to be violated if the object is ever to have its dependency fulfilled" The founding premise of your reply is simply untrue. As @Rogério states newing up a dependency internally, and any other method where an object internally satifies its own dependencies does not violate encapsulation. – Neutrino Oct 25 '17 at 19:16
18

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!
}
topright gamedev
  • 2,617
  • 7
  • 35
  • 53
  • 3
    "Those are my principles, and if you don't like them... well, I have others." (Groucho Marx) – Ron Inbar Mar 31 '15 at 15:40
  • 2
    I think this is sort of the point. It's dependant injection vs encapsulation. So only use dependant injection where it gives significant benifits. It's the DI everywhere that gives DI a bad name – Richard Tingle Oct 18 '15 at 17:26
  • 1
    Not sure what this answer is trying to say... That it's ok to violate encapsulation when doing DI, that it's "always ok" because it would be violated anyway, or merely that DI *might* be a reason to violate encapsulation? On another note, these days there is no need anymore to rely on *public* constructors or properties in order to inject dependencies; instead, we can inject into *private annotated fields*, which is simpler (less code) and preserves encapsulation. So, we can take advantage of both principles at the same time. – Rogério Aug 29 '16 at 17:07
  • Inheritance does not in principle violate encapsulation, though it may do if the parent class is badly written. The other points you raise are one fairly fringe programming paradigm and several language features that have little to do with architecture or design. – Neutrino Oct 25 '17 at 19:27
12

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?

Rogério
  • 16,171
  • 2
  • 50
  • 63
  • 2
    Thinking ahead isn't terrible, but I agree Keep It Simple, Stupid, especially if You Ain't Gonna Need It! I've seen developers waste cycles because they are over designing something to be too future proof, and based on hunches at that, not even business requirements that are known/suspected. – Jacob McKay May 18 '16 at 04:22
6

A good depenancy injection container/system will allow for constructor injection. The dependant objects will be encapsulated, and need not be exposed publicly at all. Further, by using a DP system, none of your code even "knows" the details of how the object is constructed, possibly even including the object being constructed. There is more encapsulation in this case since nearly all of your code not only is shielded from knowledge of the encapsulated objects, but does not even participate in the objects construction.

Now, I am assuming you are comparing against the case where the created object creates its own encapsulated objects, most likely in its constructor. My understanding of DP is that we want to take this responsibility away from the object and give it to someone else. To that end, the "someone else", which is the DP container in this case, does have intimate knowledge which "violates" encapsulation; the benefit is that it pulls that knowledge out of the object, iteself. Someone has to have it. The rest of your application does not.

I would think of it this way: The dependancy injection container/system violates encapsulation, but your code does not. In fact, your code is more "encapsulated" then ever.

Bill
  • 2,381
  • 4
  • 21
  • 24
  • 3
    If you have a situation where the client object CAN instantiate its dependencies directly, then why not do so? It's definitely the simplest thing to do, and does not necessarily reduce testability. Besides the simplicity and better encapsulation, this also makes it easier to have stateful objects instead of stateless singletons. – Rogério Jul 21 '09 at 22:40
  • 1
    Adding to what @Rogério said it's also potentially significantly more efficient. Not every class ever created in the history of the world needed to have every single one of its dependencies instantiated for the entirety of the owning object's lifetime. An object using DI loses the most basic control of its own dependencies, namely their lifetime. – Neutrino Oct 25 '17 at 19:23
5

This is similar to the upvoted answer but I want to think out loud - perhaps others see things this way as well.

  • Classical OO uses constructors to define the public "initialization" contract for consumers of the class (hiding ALL implementation details; aka encapsulation). This contract can ensure that after instantiation you have a ready-to-use object (i.e. no additional initialization steps to be remembered (er, forgotten) by the user).

  • (constructor) DI undeniably breaks encapsulation by bleeding implemenation detail through this public constructor interface. As long as we still consider the public constructor responsible for defining the initialization contract for users, we have created a horrible violation of encapsulation.

Theoretical Example:

Class Foo has 4 methods and needs an integer for initialization, so its constructor looks like Foo(int size) and it's immediately clear to users of class Foo that they must provide a size at instantiation in order for Foo to work.

Say this particular implementation of Foo may also need a IWidget to do its job. Constructor injection of this dependency would have us create a constructor like Foo(int size, IWidget widget)

What irks me about this is now we have a constructor that's blending initialization data with dependencies - one input is of interest to the user of the class (size), the other is an internal dependency that only serves to confuse the user and is an implementation detail (widget).

The size parameter is NOT a dependency - it's simple a per-instance initialization value. IoC is dandy for external dependencies (like widget) but not for internal state initialization.

Even worse, what if the Widget is only necessary for 2 of the 4 methods on this class; I may be incurring instantiation overhead for Widget even though it may not be used!

How to compromise/reconcile this?

One approach is to switch exclusively to interfaces to define the operation contract; and abolish the use of constructors by users. To be consistent, all objects would have to be accessed through interfaces only, and instantiated only through some form of resolver (like an IOC/DI container). Only the container gets to instantiate things.

That takes care of the Widget dependency, but how do we initialize "size" without resorting to a separate initialization method on the Foo interface? Using this solution, we lost the ability to ensure that an instance of Foo is fully initialized by the time you get the instance. Bummer, because I really like the idea and simplicity of constructor injection.

How do I achieve guaranteed initialization in this DI world, when initialization is MORE than ONLY external dependencies?

shawnT
  • 398
  • 2
  • 8
  • Update: I just noticed Unity 2.0 supports providing values for constructor parameters (such as state initializers), while still using normal mechanism for IoC of dependencies during resolve(). Perhaps other containers also support this? That solves the technical difficulty of mixing state init and DI in one constructor, but it still violates encapsulation! – shawnT Feb 26 '10 at 05:06
  • I hear ya. I asked this question because I too feel that two good things (DI & encapsulation) come one at the expense of the other. BTW, in your example where only 2 out of 4 methods need the IWidget, that would indicate that the other 2 belong in a different component IMHO. – urig Mar 04 '10 at 16:18
5

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.

kyoryu
  • 12,848
  • 2
  • 29
  • 33
  • I definitely agree with you about the first definition. It also violates SoC which is arguably one of the cardinal sins of programming and probably one of the reasons it doesn't scale. – Marcus Stade Sep 01 '10 at 14:05
4

It doesn't violate encapsulation. You're providing a collaborator, but the class gets to decide how it is used. As long as you follow Tell don't ask things are fine. I find constructer injection preferable, but setters can be fine as well as long as they're smart. That is they contain logic to maintain the invariants the class represents.

Jason Watkins
  • 2,702
  • 17
  • 18
  • Thanks for your reply and for the link. Can you elaborate on why you think this doesn't violate encapsulation? If you take a look here: http://tinyurl.com/cscynq , you'll find almost every tenet of encapsulation is violated by having a dependency exposed publicly. – urig Jun 17 '09 at 08:15
  • 1
    Because it... doesn't? If you have a logger, and you have a class that needs the logger, passing the logger to that class does not violate encapsulation. And that's all dependency injection is. – jrockway Jun 17 '09 at 14:19
  • 3
    I think you misunderstand encapsulation. For example, take a naive date class. Internally it might have day, month and year instance variables. If these were exposed as simple setters with no logic, this would break encapsulation, since I could do something like set month to 2 and day to 31. On the other hand, if the setters are smart and check the invariants, then things are fine. Also notice that in the latter version, I could change the storage to be days since 1/1/1970, and nothing that used the interface need be aware of this provided I appropriately rewrite the day/month/year methods. – Jason Watkins Jun 18 '09 at 00:46
  • 4
    DI definitely does violate encapsulation/information hiding. If you turn a private internal dependency into something exposed in the public interface of the class, then by definition you have broken the encapsulation of that dependency. – Rogério Jul 21 '09 at 22:52
  • 2
    I have a concrete example where I think encapsulation is compromised by DI. I have an FooProvider that gets "foo data" from the DB and a FooManager that caches it and calculates stuff on top of the provider. I had consumers of my code mistakenly going to the FooProvider for data, where I'd rather have had it encapsulated away so they are only aware of the FooManager. This is basically the trigger for my original question. – urig Jan 15 '10 at 18:20
  • @urig - can FooManager work without a connection string? If not, it hasn't really encapsulated the FooProvider. – Jeff Sternal Mar 24 '10 at 00:43
  • 1
    @Rogerio: I would argue that the constructor is *not* part of the public interface, as it's only used in the composition root. Thus, the dependency is only "seen" by the composition root. The composition root's single responsibility is to wire these dependencies together. So using constructor injection does not break any encapsulation. – Jay Sullivan Feb 12 '13 at 07:01
3

Having struggled with the issue a little further, I am now in the opinion that Dependency Injection does (at this time) violate encapsulation to some degree. Don't get me wrong though - I think that using dependency injection is well worth the tradeoff in most cases.

The case for why DI violates encapsulation becomes clear when the component you are working on is to be delivered to an "external" party (think of writing a library for a customer).

When my component requires sub-components to be injected via the constructor (or public properties) there's no guarantee for

"preventing users from setting the internal data of the component into an invalid or inconsistent state".

At the same time it cannot be said that

"users of the component (other pieces of software) only need to know what the component does, and cannot make themselves dependent on the details of how it does it".

Both quotes are from wikipedia.

To give a specific example: I need to deliver a client-side DLL that simplifies and hides communication to a WCF service (essentially a remote facade). Because it depends on 3 different WCF proxy classes, if I take the DI approach I am forced to expose them via the constructor. With that I expose the internals of my communication layer which I am trying to hide.

Generally I am all for DI. In this particular (extreme) example, it strikes me as dangerous.

urig
  • 16,016
  • 26
  • 115
  • 184
3

Pure encapsulation is an ideal that can never be achieved. If all dependencies were hidden then you wouldn't have the need for DI at all. Think about it this way, if you truly have private values that can be internalized within the object, say for instance the integer value of the speed of a car object, then you have no external dependency and no need to invert or inject that dependency. These sorts of internal state values that are operated on purely by private functions are what you want to encapsulate always.

But if you're building a car that wants a certain kind of engine object then you have an external dependency. You can either instantiate that engine -- for instance new GMOverHeadCamEngine() -- internally within the car object's constructor, preserving encapsulation but creating a much more insidious coupling to a concrete class GMOverHeadCamEngine, or you can inject it, allowing your Car object to operate agnostically (and much more robustly) on for example an interface IEngine without the concrete dependency. Whether you use an IOC container or simple DI to achieve this is not the point -- the point is that you've got a Car that can use many kinds of engines without being coupled to any of them, thus making your codebase more flexible and less prone to side effects.

DI is not a violation of encapsulation, it is a way of minimizing the coupling when encapsulation is necessarily broken as a matter of course within virtually every OOP project. Injecting a dependency into an interface externally minimizes coupling side effects and allows your classes to remain agnostic about implementation.

Dave Sims
  • 5,060
  • 3
  • 24
  • 26
3

It depends on whether the dependency is really an implementation detail or something that the client would want/need to know about in some way or another. One thing that is relevant is what level of abstraction the class is targeting. Here are some examples:

If you have a method that uses caching under the hood to speed up calls, then the cache object should be a Singleton or something and should not be injected. The fact that the cache is being used at all is an implementation detail that the clients of your class should not have to care about.

If your class needs to output streams of data, it probably makes sense to inject the output stream so that the class can easily output the results to an array, a file, or wherever else someone else might want to send the data.

For a gray area, let's say you have a class that does some monte carlo simulation. It needs a source of randomness. On the one hand, the fact that it needs this is an implementation detail in that the client really doesn't care exactly where the randomness comes from. On the other hand, since real-world random number generators make tradeoffs between degree of randomness, speed, etc. that the client may want to control, and the client may want to control seeding to get repeatable behavior, injection may make sense. In this case, I'd suggest offering a way of creating the class without specifying a random number generator, and use a thread-local Singleton as the default. If/when the need for finer control arises, provide another constructor that allows for a source of randomness to be injected.

dsimcha
  • 67,514
  • 53
  • 213
  • 334
2

I struggled with this notion as well. At first, the 'requirement' to use the DI container (like Spring) to instantiate an object felt like jumping thru hoops. But in reality, it's really not a hoop - it's just another 'published' way to create objects I need. Sure, encapsulation is 'broken' becuase someone 'outside the class' knows what it needs, but it really isn't the rest of the system that knows that - it's the DI container. Nothing magical happens differently because DI 'knows' one object needs another.

In fact it gets even better - by focusing on Factories and Repositories I don't even have to know DI is involved at all! That to me puts the lid back on encapsulation. Whew!

n8wrl
  • 19,439
  • 4
  • 63
  • 103
  • 3
    As long as DI is in charge of the entire chain of instantiation, then I agree that encapsulation sort of occurs. Sort of, because the dependencies are still public and can be abused. But when somewhere "up" in the chain someone needs to instantiate an object without them using DI (maybe they're a "third party") then it gets messy. They are exposed to your dependencies and might be tempted to abuse them. Or they might not want to know about them at all. – urig Jun 28 '09 at 16:11
2

I belive in simplicity. Applying IOC/Dependecy Injection in Domain classes does not make any improvement except making the code much more harder to main by having an external xml files describing the relation. Many technologies like EJB 1.0/2.0 & struts 1.1 are reversing back by reducing the stuff the put in XML and try put them in code as annoation etc. So applying IOC for all the classes you develope will make the code non-sense.

IOC has it benefits when the dependent object is not ready for creation at compile time. This can happend in most of the infrasture abstract level architecture components, trying establish a common base framework which may need to work for different scenarios. In those places usage IOC makes more sense. Still this does not make the code more simple / maintainable.

As all the other technologies, this too has PROs & CONs. My worry is, we implement latest technologies in all the places irrespective of their best context usage.

2

DI violates Encapsulation for NON-Shared objects - period. Shared objects have a lifespan outside of the object being created, and thus must be AGGREGATED into the object being created. Objects that are private to the object being created should be COMPOSED into the created object - when the created object is destroyed, it takes the composed object with it. Let's take the human body as an example. What's composed and what's aggregated. If we were to use DI, the human body constructor would have 100's of objects. Many of the organs, for example, are (potentially) replaceable. But, they are still composed into the body. Blood cells are created in the body (and destroyed) everyday, without the need for external influences (other than protein). Thus, blood cells are created internally by the body - new BloodCell().

Advocators of DI argue that an object should NEVER use the new operator. That "purist" approach not only violates encapsulation but also the Liskov Substitution Principle for whoever is creating the object.

urig
  • 16,016
  • 26
  • 115
  • 184
Greg Brand
  • 21
  • 2
2

Encapsulation is only broken if a class has both the responsibility to create the object (which requires knowledge of implementation details) and then uses the class (which does not require knowledge of these details). I'll explain why, but first a quick car anaology:

When I was driving my old 1971 Kombi, I could press the accelerator and it went (slightly) quicker. I did not need to know why, but the guys who built the Kombi at the factory knew exactly why.

But back to the coding. Encapsulation is "hiding an implementation detail from something using that implementation." Encapsulation is a good thing because the implementation details can change without the user of the class knowing.

When using dependency injection, constructor injection is used to construct service type objects (as opposed to entity/value objects which model state). Any member variables in service type object represent implementation details that should not leak out. e.g. socket port number, database credentials, another class to call to perform encryption, a cache, etc.

The constructor is relevant when the class is being initially created. This happens during the construction-phase while your DI container (or factory) wires together all the service objects. The DI container only knows about implementation details. It knows all about implementation details like the guys at the Kombi factory know about spark plugs.

At run-time, the service object that was created is called apon to do some real work. At this time, the caller of the object knows nothing of the implementation details.

That's me driving my Kombi to the beach.

Now, back to encapsulation. If implementation details change, then the class using that implementation at run-time does not need to change. Encapsulation is not broken.

I can drive my new car to the beach too. Encapsulation is not broken.

If implementation details change, the DI container (or factory) does need to change. You were never trying to hide implementation details from the factory in the first place.

WW.
  • 23,793
  • 13
  • 94
  • 121
  • How would you unit test your factory? And that means the client needs to know about the factory in order to get a working car, which means you need a factory for each other object in your system. – Rodrigo Ruiz Apr 23 '15 at 21:57
1

PS. By providing Dependency Injection you do not necessarily break Encapsulation. Example:

obj.inject_dependency(  factory.get_instance_of_unknown_class(x)  );

Client code does not know implementation details still.

topright gamedev
  • 2,617
  • 7
  • 35
  • 53
  • How in your example is anything injected? (Except for the naming of your setter function) – foo Feb 13 '19 at 21:36
1

Maybe this is a naive way of thinking about it, but what is the difference between a constructor that takes in an integer parameter and a constructor that takes in a service as a parameter? Does this mean that defining an integer outside the new object and feeding it into the object breaks encapsulation? If the service is only used within the new object, I don't see how that would break encapsulation.

Also, by using some sort of autowiring feature (Autofac for C#, for example), it makes the code extremely clean. By building extension methods for the Autofac builder, I was able to cut out a LOT of DI configuration code that I would have had to maintain over time as the list of dependencies grew.

blooware
  • 11
  • 1
  • It's not about value vs. service. It is about inversion of control - whether the constructor of the class sets up the class, or whether that service takes over setting up the class. For which it needs to know implementation details of that class, so you got another place to maintain and sync. – foo Feb 13 '19 at 21:35
1

I think it's self evident that at the very least DI significantly weakens encapsulation. In additional to that here are some other downsides of DI to consider.

  1. It makes code harder to reuse. A module which a client can use without having to explicitly provide dependencies to, is obviously easier to use than one where the client has to somehow discover what that component's dependencies are and then somehow make them available. For example a component originally created to be used in an ASP application may expect to have its dependencies provided by a DI container that provides object instances with lifetimes related to client http requests. This may not be simple to reproduce in another client that does not come with the same built in DI container as the original ASP application.

  2. It can make code more fragile. Dependencies provided by interface specification can be implemented in unexpected ways which gives rise to a whole class of runtime bugs that are not possible with a statically resolved concrete dependency.

  3. It can make code less flexible in the sense that you may end up with fewer choices about how you want it to work. Not every class needs to have all its dependencies in existence for the entire lifetime of the owning instance, yet with many DI implementations you have no other option.

With that in mind I think the most important question then becomes, "does a particular dependency need to be externally specified at all?". In practise I have rarely found it necessary to make a dependency externally supplied just to support testing.

Where a dependency genuinely needs to be externally supplied, that normally suggests that the relation between the objects is a collaboration rather than an internal dependency, in which case the appropriate goal is then encapsulation of each class, rather than encapsulation of one class inside the other.

In my experience the main problem regarding the use of DI is that whether you start with an application framework with built in DI, or you add DI support to your codebase, for some reason people assume that since you have DI support that must be the correct way to instantiate everything. They just never even bother to ask the question "does this dependency need to be externally specified?". And worse, they also start trying to force everyone else to use the DI support for everything too.

The result of this is that inexorably your codebase starts to devolve into a state where creating any instance of anything in your codebase requires reams of obtuse DI container configuration, and debugging anything is twice as hard because you have the extra workload of trying to identify how and where anything was instantiated.

So my answer to the question is this. Use DI where you can identify an actual problem that it solves for you, which you can't solve more simply any other way.

Neutrino
  • 8,496
  • 4
  • 57
  • 83
0

I think it's a matter of scope. When you define encapsulation (not letting know how) you must define what is the encapsuled functionality.

  1. Class as is: what you are encapsulating is the only responsability of the class. What it knows how to do. By example, sorting. If you inject some comparator for ordering, let's say, clients, that's not part of the encapsuled thing: quicksort.

  2. Configured functionality: if you want to provide a ready-to-use functionality then you are not providing QuickSort class, but an instance of QuickSort class configured with a Comparator. In that case the code responsible for creating and configuring that must be hidden from the user code. And that's the encapsulation.

When you are programming classes, it is, implementing single responsibilities into classes, you are using option 1.

When you are programming applications, it is, making something that undertakes some useful concrete work then you are repeteadily using option 2.

This is the implementation of the configured instance:

<bean id="clientSorter" class="QuickSort">
   <property name="comparator">
      <bean class="ClientComparator"/>
   </property>
</bean>

This is how some other client code use it:

<bean id="clientService" class"...">
   <property name="sorter" ref="clientSorter"/>
</bean>

It is encapsulated because if you change implementation (you change clientSorter bean definition) it doesn't break client use. Maybe, as you use xml files with all written together you are seeing all the details. But believe me, the client code (ClientService) don't know nothing about its sorter.

helios
  • 13,574
  • 2
  • 45
  • 55
0

It's probably worth mentioning that Encapsulation is somewhat perspective dependent.

public class A { 
    private B b;

    public A() {
        this.b = new B();
    }
}


public class A { 
    private B b;

    public A(B b) {
        this.b = b;
    }
}

From the perspective of someone working on the A class, in the second example A knows a lot less about the nature of this.b

Whereas without DI

new A()

vs

new A(new B())

The person looking at this code knows more about the nature of A in the second example.

With DI, at least all that leaked knowledge is in one place.

Tom B
  • 2,735
  • 2
  • 24
  • 30
0

I agree that taken to an extreme, DI can violate encapsulation. Usually DI exposes dependencies which were never truly encapsulated. Here's a simplified example borrowed from Miško Hevery's Singletons are Pathological Liars:

You start with a CreditCard test and write a simple unit test.

@Test
public void creditCard_Charge()
{
    CreditCard c = new CreditCard("1234 5678 9012 3456", 5, 2008);
    c.charge(100);
}

Next month you get a bill for $100. Why did you get charged? The unit test affected a production database. Internally, CreditCard calls Database.getInstance(). Refactoring CreditCard so that it takes a DatabaseInterface in its constructor exposes the fact that there's dependency. But I would argue that the dependency was never encapsulated to begin with since the CreditCard class causes externally visible side effects. If you want to test CreditCard without refactoring, you can certainly observe the dependency.

@Before
public void setUp()
{
    Database.setInstance(new MockDatabase());
}

@After
public void tearDown()
{
    Database.resetInstance();
}

I don't think it's worth worrying whether exposing the Database as a dependency reduces encapsulation, because it's a good design. Not all DI decisions will be so straight forward. However, none of the other answers show a counter example.

Craig P. Motlin
  • 26,452
  • 17
  • 99
  • 126
  • 1
    Unit tests are usually written by the class author, so it's ok to spell out the dependencies in the test case, from a technical point of view. When later credit card class changes to use a Web API such as PayPal, the user would need to change everything if it was DIed. Unit testing are usually done with intimate knowledge of the subject being tested (isn't that the whole point?) so I think tests are more of an exception than a typical example. – kizzx2 Sep 20 '10 at 11:33
  • 1
    The point of DI is to avoid the changes you described. If you switched from a Web API to PayPal, you wouldn't change most tests because they'd use a MockPaymentService and CreditCard would get constructed with a PaymentService. You'd have just a handful of tests looking at the real interaction between CreditCard and a real PaymentService, so future changes are very isolated. The benefits are even greater for deeper dependency graphs (such as a class that depends on CreditCard). – Craig P. Motlin Sep 20 '10 at 18:18
  • @Craig p. Motlin How can the `CreditCard` object change from a WebAPI to PayPal, without anything external to the class having to change? – Ian Boyd Sep 29 '10 at 14:46
  • @Ian I mentioned CreditCard should be refactored to take a DatabaseInterface in its constructor which shields it from changes in the implementations of DatabaseInterfaces. Maybe that needs to be even more generic, and take a StorageInterface of which WebAPI could be another implementation. PayPal is at the wrong level though, because it's an alternative to CreditCard. Both PayPal and CreditCard could implement PaymentInterface to shield other parts of the application from outside this example. – Craig P. Motlin Oct 05 '10 at 15:47
  • @kizzx2 In other words, it's nonsense to say a credit card should use PayPal. They are alternatives in real life. – Craig P. Motlin Oct 05 '10 at 15:48
  • @Craig Maybe our semantics got a little confused. The main thing is that if you DI and you want to change your internal implementation, it's less transparent and violates encapsulation (as the question title). If you didn't use DI, nobody knows you have changed your internal implementation, so you're encapsulated. Consider this: If all your dependencies are DI'ed, you must rely on very generic interfaces and you must not downcast (because you don't know the concrete class supplied by your client). This works out in very pure scenarios but gets quite inflexible and limiting in real world, IMO. – kizzx2 Oct 06 '10 at 05:45
  • @kizzx2 If you wanted to change CreditCard to persist somewhere other than a database, and if you're doing DI right, there should be exactly one place in your program where the text needs to change. You don't even need a container to achieve that, you can do it by hand. If the user really needs to change everything then either the DI pattern wasn't applied properly, or my original point is even more pronounced, that usually DI exposes dependencies which were never truly encapsulated. – Craig P. Motlin Oct 06 '10 at 15:30
  • @Craig the point was that DI does in some instance sacrifice encapsulation, as mentioned in your original answer. Anyway, my original comment was mainly about test case being a non representative example for the reason I stated. – kizzx2 Oct 07 '10 at 00:55
  • @kizzx2 The test case only needs to be refactored if you are not using DI. It is meant to demonstrate that the dependency on the Database was never encapsulated at all, and after moving to DI, it's at least encapsulated behind an interface. – Craig P. Motlin Oct 07 '10 at 20:24
  • @CraigP.Motlin Using DI in your example makes the client of you CreditCard class have to know about the existence of a Database. How do I manage to charge a CreditCard without know that it is saved to a database? – Rodrigo Ruiz Apr 23 '15 at 22:06