3 ms·
Not at all. Suppose you need a stapler for some work. You don't have one, but you know a colleague who does and who is willing to happily share it with you. Yo
by jpatte 13y ago
Not at all.
Suppose you need a stapler for some work. You don't have one, but you know a colleague who does and who is willing to happily share it with you. You could go to her office, open the second drawer in her desk, take the stapler and leave. Or you could just ask her to give it to you. In both case the result is the same: you will get the stapler.
But there is a major difference : in the first case, you had to know where the stapler was. Your colleague knows it - it's her desk, after all - but because you decide to ignore the service she can provide and do it yourself, you have to know it as well. That means that you are both dependent of the manner of accessing the stapler.
What if someday she decides to move the stapler into the third drawer ? Because of this dependency, you would have to be informed of this change and start behaving accordingly. Your implementation would be impacted by a change in her implementation. And this is bad.
On the contrary, if you just asked her to give you the stapler, it wouldn't matter at all where it's stored. As the owner of this item she would the sole responsible for its location, and your behavior would never be impacted.
This is the purpose of encapsulation: preventing objects implementations from being impacted by changes in other objets implementations. You should be applying this everywhere, every times. Even for such small services as "give me that value, please". In your example, you should not need to know if a field or anything else is used to store the value because it's an implementation concern. You should just ask the value to the object.