4 ms·
> That's not what encapsulation means Then what does encapsulation mean? If encapsulation means that an object protects all of its private state behind methods
by taffer 5y ago
> That's not what encapsulation means
Then what does encapsulation mean? If encapsulation means that an object protects all of its private state behind methods, then another object must not be able to manipulate that private state. So if an object A holds a reference to another object B, then B's state becomes part of A's state and only A must be able to do things that change B.
- kaba0 5y agoOOP only strives to encapsulate private state (though don’t forget that too strict rules never make sense. In the end, every design pattern needs an escape hatch). All the methods of the object should modify these in a way that upholds the class invariants. In your example, B can easily be part of the “public state” of the object, or we can make even more gradual distinctions, like only B’s identity is relevant for A’s state. For example, if A only needs B as optional cache, its modification or even removal will not be a problem.
- taffer 5y agoThis concept of "public state" makes no sense to me. If the behavior of A, i.e. the implementation of A, depends on B, then changing the state of B will also change the behavior of A as a side effect. Otherwise, if B were "public state", then B would be nothing more than a glorified global variable and you would have exactly the free for all access that OOP is supposed to prevent. So the only way to prevent this is that each object must have only one parent in the object tree, which coordinates all modifications to that object. Regarding escape hatches: Yes, it's great to have them, but it's not so great when they are used all the time, either by accident because it's so easy to break OO rules, or on purpose because the object tree gets in the way when new requirements need to be implemented. Let's be honest here: The more mature an OO-designed project becomes, the more shortcuts there will be and the cross-connections aka "escape hatches" will turn the object tree into an object spaghetti.