What you’ve provided here is a workaround for the fact that Encapsulation is flawed when passing by…
Charles Scalfani
156

Charles, no inheritance shouldn’t be seen as the catch-all tool for code reuse. You’re right that it only fits things that are specifically a sub-category of another. And the more of a jungle of broad talents you give a class the more likely that more specific sub-classes will actually only want a banana. But it’s not a very easy problem to solve because a rich, multi-talented object can be a wonderful thing for programmer productivity if not performance.

I agree that yes, the private instance variables won’t cast-iron protect you from what’s going on outside without having to think. Yes, that makes encapsulation a commonly overstated benefit.

However, the difference between storing references and literals is a key concept any OO programmer will be introduced to early on. It isn’t a surprising gotcha.

If you’re trying to use one object as part of the private state of another one I would have to ask why you made that contained instance available to anything else. If it got created elsewhere and your parent instance went and gobbled it up through its public face that suggests the child has a right to a non-private life. In which case storing it by reference might reflect the real world complexity you’re modelling.

If that particular instance should be totally encapsulated then make sure the private var can only be set by creating the object bespoke by the containing object.