Search code examples
oopdesign-patternsencapsulation

Doesn't property dependency injection violates the principle of encapsulation?


The mechanism to put data & methods that operate on these data, together in a class is called as encapsulation.

However to follow Open/Closed principle, Dependency injection is achieved by exposing public properties.

In this case encapsulation & Dependency injection seems contradicting each other, isn't it?


Solution

  • There are two different things to consider here. Let's use a simple "Person" example.

    The properties of a person might include firstName, lastName, dateOfBirth and so on. To preserve encapsulation, these might be private. If you needed the person's age, you would have to ask the Person object to give you the age and it would use its private dateOfBirth to calculate the age. This prevents the logic of getting a person's age from being duplicated in many places in the system, which might be encouraged if dateOfBirth was public.

    The Person object may also have dependencies on other objects. Rather than create these objects itself, the person relies on some other entity in the system to create the dependencies and pass them in. The Person object may expose public properties to hold these dependencies (or methods to set the dependencies) - these are not the properties of a person, they are the dependencies of a person.

    This is actually another example of having logic in only one place - you have one "thing" in your system that can create a dependency, rather than having many objects all creating that dependency for themselves.