oop - Doesn't property depency injection violates the principle of encapsulation? -


the mechanism put data & methods operate on these data, in class called encapsulation.

however follow open/closed principle, dependency injection achieved exposing public properties.

in case encapsulation & dependency injection seems contradicting each other, isn't ?

there 2 different things consider here. let's use simple "person" example.

the properties of person might include firstname, lastname, dateofbirth , on. preserve encapsulation, these might private. if needed person's age, have ask person object give age , use private dateofbirth calculate age. prevents logic of getting person's age being duplicated in many places in system, might encouraged if dateofbirth public.

the person object may have dependencies on other objects. rather create these objects itself, person relies on other entity in system create dependencies , pass them in. person object may expose public properties hold these dependencies (or methods set dependencies) - these not properties of person, dependencies of person.

this example of having logic in 1 place - have 1 "thing" in system can create dependency, rather having many objects creating dependency themselves.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -