Sorry about previous post.
I wonder how to solve the problem of encapsulation in aggregated objects. Example:
|
Now if we write the constructor code in version 1, then create an instance of SafeClass:
|
It is possible to modify internals of SafeClass from outside. We can simply solve the problem:
|
But we can assume, that developer using our SafeClass forget to clone the cm object before passing it to the constructor. In such situation SafeClass would be vulnerable to modification internals from outside. If we decided to clone CustomModel in constructor of SafeClass (version 2), our class would be safe. What if client of SafeClass is aware of risk related to passing references to other objects. Let's assume he don't know the code of SafeClass(he don't have to) and intentionally clone the parameter of SafeClass constructor (as shown above). In that way, CustomModel would be cloned twice.
What do you think about that ? What are the best practices for encapsulation in such situation ?
Regards
PatrykPosted Aug 6, 2009, 10:41 AM
do the same.
As i wrote earlier, we can eliminate the possibility of modyfication internal data of SafeClass by cloning CustomModel in constructor. But in can lead to cloning object twice.
Preetham MukhatiraPosted Aug 6, 2009, 10:04 AM
Since they are int values, a shallow copy will allocate new bits. MemberwiseClone() does a shallow copy
Also, when implementing an interface you should not use the "override" option.